• CompletableFuture相关用法


    由于guava中Listenablefuture的成功,在Java 8中,设计师们也新加了一个包含50个方法左右的类CompletableFuture。它的优点就是异步编程,同时这个类的使用也相当抽象…非常抽象

    构造

    它可以直接被new出来,此时它被当做Future来使用

    CompletableFuture<Object> completableFuture = new CompletableFuture<Object>();
    //传入参数,这个方法只能调用一次
    completableFuture.complete(rpcResponse);
    //传入异常,这个方法只能调用一次
    completableFuture.completeExceptionally()
    //用isDone来判断任务是否执行完毕
    completableFuture.isDone();
    //输出里面存的值
    System.out.println(completableFuture.get());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    但是在一般的使用中我们不会这么简单,来看看正常的构造

    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor);
    
    public static CompletableFuture<Void> runAsync(Runnable runnable);
    public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);
    
    • 1
    • 2
    • 3
    • 4
    • 5

    supply族的方法,可以返回异步线程执行之后的结果
    run族的方法不会返回结果,像Runnable一样就只是执行线程任务

    而且一般使用带线程池的方法,如果不这么做的化,该方法就会默认使用系统及公共线程池ForkJoinPool,而且这些线程都是守护线程。如果将我们普通的用户线程设置成守护线程,当我们的程序主线程结束,JVM中不存在其余用户线程,那么CompletableFuture的守护线程会直接退出,造成任务无法完成的问题

    总之,不要用默认的线程池!下面是个正常的例子

            CompletableFuture<Object> completableFuture = CompletableFuture.supplyAsync(new Supplier<Object>() {
                @Override
                public Object get() {
                    return null;
                }
            }, MyThreadPool.getPoolExecutor());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    supplyAsync()方法接受的参数是Supplier,它是一个功能接口,代表结果的提供者

    Supplier只有一个get()方法,可以返回通用类型的值,在这里它的返回值就是CompletableFuture里存的值,而接口所传入的参数类型就是返回值的参数类型

    获取结果

    以下是可以拿到CompletableFuture中存放的值的方法

    public T    get()
    public T    get(long timeout, TimeUnit unit)
    public T    getNow(T valueIfAbsent)
    public T    join()
    
    • 1
    • 2
    • 3
    • 4

    处理结果

    这是CompletableFuture的灵魂,我们可以用一些方法对得到的CompletableFuture进行进一步的处理

    public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
    public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
    
    public <U> CompletableFuture<U> handle(BiFunction<? super T,Throwable,? extends U> fn)
    public <U> CompletableFuture<U> handleAsync(BiFunction<? super T,Throwable,? extends U> fn)
    public <U> CompletableFuture<U> handleAsync(BiFunction<? super T,Throwable,? extends U> fn, Executor executor)
    
    public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
    public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
    
    public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
    
    public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    找不同,来找找他们有什么相同点?

    • 四组里所有带Executor executor的方法都是传入一个自己的线程池去执行,不带的则是使用默认线程池
    • 四组里所有不带Async的方法都不使用异步处理
    • whenComplete组都会提供,一个返回结果和可抛出异常
    • handle组同样提供两个参数,一个返回结果和可抛出异常,与whenComplete组区别就是可以返回自定义参数类型的CompletableFuture
    • thenApply组只提供一个返回结果,并且可以返回自定义参数类型的CompletableFuture,同时,两个异步计算之间相互独立,互不依赖
    • thenAccept返回的CompletableFuture是空返回,不能从回调函数中获取返回结果,用这个组的方法来终结链式调用。与这个相似的是thenRun组的方法,区别是thenRun组不能访问异步计算的结果
    • exceptionally方法直接抓获所有异常

    以下是一个简单的lamda表达式的例子,thenApply中Function接口只需要实现一个apply方法,接口传入的第一个参数是方法的入参类型,第二个是返回值类型

            CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync((Supplier<Object>) () -> "hello", MyThreadPool.getPoolExecutor())
                    .thenApply(s -> s + "world");
            System.out.println(completableFuture.get());
    
    • 1
    • 2
    • 3

    组合

    CompletableFuture提供一些方法按顺序链接两个CompletableFuture对象

    public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)
    public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn)
    public <U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn,Executor executor)
    
    • 1
    • 2
    • 3

    该方法可以按顺序链接两个CompletableFuture对象,它会将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序

    thenCombine组同样可以组合两个CompletableFuture对象,它会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序

    并行运行任务

    CompletableFuture使用静态的allOf与anyOf来并行运行任务,中间的task1到task6都是CompletableFuture对象

    CompletableFuture<Void> headerFuture = CompletableFuture.allOf(task1,.....,task6);
    CompletableFuture<Void> headerFuture = CompletableFuture.anyOf(task1,.....,task6);
    
    • 1
    • 2

    allOf方法等待所有任务执行完毕之后才返回,join() 可以让程序等任务都运行完了之后再继续执行
    anyOf只等待第一个任务执行完毕之后就返回,如果任务错误也会返回异常

  • 相关阅读:
    win11开启护眼模式设置
    牛客网《剑指offer》专栏刷题练习之双指针算法的使用
    RedissonCach的源码流程
    【CocosCreator】利用遮罩Mask实现单边开门效果
    flink job同时使用BroadcastProcessFunction和KeyedBroadcastProcessFunction例子
    web安全——sql注入漏洞知识点总结
    测试用例:在线音乐播放器
    正式发布!Matlab配色神器TheColor
    设备管理的未来是什么?5 对未来的预测
    xss-labs/level9
  • 原文地址:https://blog.csdn.net/sekever/article/details/125898778