zoukankan      html  css  js  c++  java
  • CompletableFuture详解

    在JDK1.5已经提供了Future和Callable的实现,可以用于阻塞式获取结果,如果想要异步获取结果,通常都会以轮询的方式去获取结果,如下:

     1 //定义一个异步任务
     2 Future<String> future = executor.submit(()->{
     3        Thread.sleep(2000);
     4        return "hello world";
     5 });
     6 //轮询获取结果
     7 while (true){
     8     if(future.isDone()) {
     9          System.out.println(future.get());
    10          break;
    11      }
    12  }

    从上面的形式看来轮询的方式会耗费无谓的CPU资源,而且也不能及时地得到计算结果.所以要实现真正的异步,上述这样是完全不够的,在Netty中,我们随处可见异步编程

    1 ChannelFuture f = serverBootstrap.bind(port).sync();
    2 f.addListener(new GenericFutureListener<Future<? super Void>>() {
    3                 @Override
    4                 public void operationComplete(Future<? super Void> future) throws Exception {
    5                     System.out.println("complete");
    6                 }
    7             });

        而JDK1.8中的CompletableFuture就为我们提供了异步函数式编程,CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。

    1. 创建CompletableFuture对象

        CompletableFuture提供了四个静态方法用来创建CompletableFuture对象:

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

    Asynsc表示异步,而supplyAsyncrunAsync不同在与前者异步返回一个结果,后者是void.第二个函数第二个参数表示是用我们自己创建的线程池,否则采用默认的ForkJoinPool.commonPool()作为它的线程池.其中Supplier是一个函数式接口,代表是一个生成者的意思,传入0个参数,返回一个结果.(更详细的可以看我另一篇文章)

    1 CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
    2             return "hello world";
    3   });
    4 System.out.println(future.get());  //阻塞的获取结果  ''helllo world"

    2. 主动计算

        以下4个方法用于获取结果

    1 //同步获取结果
    2 public T    get()
    3 public T    get(long timeout, TimeUnit unit)
    4 public T    getNow(T valueIfAbsent)
    5 public T    join()

    getNow有点特殊,如果结果已经计算完则返回结果或者抛出异常,否则返回给定的valueIfAbsent值。join()get()区别在于join()返回计算的结果或者抛出一个unchecked异常(CompletionException),而get()返回一个具体的异常.

    • 主动触发计算.
    1 public boolean complete(T  value)
    2 public boolean completeExceptionally(Throwable ex)

    上面方法表示当调用CompletableFuture.get()被阻塞的时候,那么这个方法就是结束阻塞,并且get()获取设置的value.

     
     1 public static CompletableFuture<Integer> compute() {
     2         final CompletableFuture<Integer> future = new CompletableFuture<>();
     3         return future;
     4     }
     5     public static void main(String[] args) throws Exception {
     6         final CompletableFuture<Integer> f = compute();
     7         class Client extends Thread {
     8             CompletableFuture<Integer> f;
     9             Client(String threadName, CompletableFuture<Integer> f) {
    10                 super(threadName);
    11                 this.f = f;
    12             }
    13             @Override
    14             public void run() {
    15                 try {
    16                     System.out.println(this.getName() + ": " + f.get());
    17                 } catch (InterruptedException e) {
    18                     e.printStackTrace();
    19                 } catch (ExecutionException e) {
    20                     e.printStackTrace();
    21                 }
    22             }
    23         }
    24         new Client("Client1", f).start();
    25         new Client("Client2", f).start();
    26         System.out.println("waiting");
    27         //设置Future.get()获取到的值
    28         f.complete(100);
    29         //以异常的形式触发计算
    30         //f.completeExceptionally(new Exception());
    31         Thread.sleep(1000);
    32     }

    3. 计算结果完成时的处理

    1 public CompletableFuture<T>     whenComplete(BiConsumer<? super T,? super Throwable> action)
    2 public CompletableFuture<T>     whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
    3 public CompletableFuture<T>     whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
    4 public CompletableFuture<T>     exceptionally(Function<Throwable,? extends T> fn)

    上面4个方法是当计算阶段结束的时候触发,BiConsumer有两个入参,分别代表计算返回值,另外一个是异常.无返回值.方法不以Async结尾,意味着Action使用相同的线程执行,而Async可能会使用其它的线程去执行(如果使用相同的线程池,也可能会被同一个线程选中执行)。

     
    1 future.whenCompleteAsync((v,e)->{
    2        System.out.println("return value:"+v+"  exception:"+e);
    3  });
    • handle()
    1 public <U> CompletableFuture<U>     handle(BiFunction<? super T,Throwable,? extends U> fn)
    2 public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn)
    3 public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn, Executor executor)

    whenComplete()不同的是这个函数返回CompletableFuture并不是原始的CompletableFuture返回的值,而是BiFunction返回的值.

    4. CompletableFuture的组合

    • thenApply
      当计算结算完成之后,后面可以接继续一系列的thenApply,来完成值的转化.
    1 public <U> CompletableFuture<U>     thenApply(Function<? super T,? extends U> fn)
    2 public <U> CompletableFuture<U>     thenApplyAsync(Function<? super T,? extends U> fn)
    3 public <U> CompletableFuture<U>     thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)

    它们与handle方法的区别在于handle方法会处理正常计算值和异常,因此它可以屏蔽异常,避免异常继续抛出。而thenApply方法只是用来处理正常值,因此一旦有异常就会抛出。

     1 CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
     2             
     3             return "hello world";
     4         });
     5 
     6 CompletableFuture<String> future3 = future.thenApply((element)->{
     7             return element+"  addPart";
     8         }).thenApply((element)->{
     9             return element+"  addTwoPart";
    10         });
    11         System.out.println(future3.get());//hello world  addPart  addTwoPart

    5. CompletableFuture的Consumer

    只对CompletableFuture的结果进行消费,无返回值,也就是最后的CompletableFuture是void.

    1 public CompletableFuture<Void>  thenAccept(Consumer<? super T> action)
    2 public CompletableFuture<Void>  thenAcceptAsync(Consumer<? super T> action)
    3 public CompletableFuture<Void>  thenAcceptAsync(Consumer<? super T> action, Executor executor)
     
    1 //入参为原始的CompletableFuture的结果.
    2 CompletableFuture future4 = future.thenAccept((e)->{
    3             System.out.println("without return value");
    4         });
    5 future4.get();
    • thenAcceptBoth

    这个方法用来组合两个CompletableFuture,其中一个CompletableFuture等待另一个CompletableFuture的结果.

    1 CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
    2             return "hello world";
    3         });
    4 CompletableFuture future5 =  future.thenAcceptBoth(CompletableFuture.completedFuture("compose"),
    5                 (x, y) -> System.out.println(x+y));//hello world compose

    6. Either和ALL

        thenAcceptBoth是当两个CompletableFuture都计算完成,而我们下面要了解的方法applyToEither是当任意一个CompletableFuture计算完成的时候就会执行。

     1 Random rand = new Random();
     2         CompletableFuture<Integer> future9 = CompletableFuture.supplyAsync(() -> {
     3             try {
     4                 Thread.sleep(1000 + rand.nextInt(1000));
     5             } catch (InterruptedException e) {
     6                 e.printStackTrace();
     7             }
     8             return 100;
     9         });
    10         CompletableFuture<Integer> future10 = CompletableFuture.supplyAsync(() -> {
    11             try {
    12                 Thread.sleep(1000 + rand.nextInt(1000));
    13             } catch (InterruptedException e) {
    14                 e.printStackTrace();
    15             }
    16             return 200;
    17         });
    18         //两个中任意一个计算完成,那么触发Runnable的执行
    19         CompletableFuture<String> f =  future10.applyToEither(future9,i -> i.toString());
    20         //两个都计算完成,那么触发Runnable的执行
    21         CompletableFuture f1 = future10.acceptEither(future9,(e)->{
    22             System.out.println(e);
    23         });
    24         System.out.println(f.get());

        如果想组合超过2个以上的CompletableFuture,allOfanyOf可能会满足你的要求.allOf方法是当所有的CompletableFuture都执行完后执行计算。anyOf方法是当任意一个CompletableFuture执行完后就会执行计算,计算的结果相同。

    总结

    有了CompletableFuture之后,我们自己实现异步编程变得轻松很多,这个类也提供了许多方法来组合CompletableFuture.结合Lambada表达式来用,变得很轻松. 

    f的whenComplete的内容由哪个线程来执行,取决于哪个线程X执行了f.complete()。但是当X线程执行了f.complete()的时候,whenComplete还没有被执行到的时候(就是事件还没有注册的时候),那么X线程就不会去同步执行whenComplete的回调了。这个时候哪个线程执行到了whenComplete的事件注册的时候,就由哪个线程自己来同步执行whenComplete的事件内容。

    而whenCompleteAsync的场合,就简单很多。一句话就是线程池里面拿一个空的线程或者新启一个线程来执行回调。和执行f.complete的线程以及执行whenCompleteAsync的线程无关。

    转自:https://www.jianshu.com/p/547d2d7761db

    参考:https://blog.csdn.net/leon_wzm/article/details/80560081

  • 相关阅读:
    PAT之我要通过
    卡拉兹(Callatz)猜想
    数组元素循环右移问题
    Reorder List
    一个fork的面试题
    内存流和null字节
    标准C IO函数和 内核IO函数 效率(时间)比较
    由fdopen和fopen想到的
    VS经常报错的link error 2019
    VS快捷键设置
  • 原文地址:https://www.cnblogs.com/fnlingnzb-learner/p/13361556.html
Copyright © 2011-2022 走看看