Java CompletableFuture详解

开发 后端
在Java 8中, 新增加了一个包含50个方法左右的类: CompletableFuture,默认依靠fork/join框架启动新的线程实现异步与并发的,提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。

 

 

Java CompletableFuture详解

在Java 8中, 新增加了一个包含50个方法左右的类: CompletableFuture,默认依靠fork/join框架启动新的线程实现异步与并发的,提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。

CompletableFuture类实现了CompletionStage和Future接口,所以可以像以前一样通过阻塞或者轮询的方式获得结果,尽管这种方式不推荐使用。

创建CompletableFuture对象。

以下四个静态方法用来为一段异步执行的代码创建CompletableFuture对象:

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

runAsync方法也好理解,它以Runnable函数式接口类型为参数,所以CompletableFuture的计算结果为空。以Async结尾会使用其它的线程去执行,没有指定Executor的方法会使用ForkJoinPool.commonPool()作为它的线程池执行异步代码。

supplyAsync方法以Supplier<U>函数式接口类型为参数,CompletableFuture的计算结果类型为U。

因为方法的参数类型都是函数式接口,所以可以使用lambda表达式实现异步任务,比如:

  1. CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     //长时间的计算任务 
  4.  
  5.     return "hello world"
  6.  
  7. }); 

计算结果完成时的处理

当CompletableFuture的计算结果完成,或者抛出异常的时候,我们可以执行特定的Action。主要是下面的方法:

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

可以看到Action的类型是BiConsumer<? super T,? super Throwable>,它可以处理正常的计算结果,或者异常情况。

注意这几个方法都会返回CompletableFuture,当Action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常。

  1. public class Main { 
  2.  
  3.     private static Random rand = new Random(); 
  4.  
  5.     private static long t = System.currentTimeMillis(); 
  6.  
  7.     static int getMoreData() { 
  8.  
  9.         System.out.println("begin to start compute"); 
  10.  
  11.         try { 
  12.  
  13.             Thread.sleep(10000); 
  14.  
  15.         } catch (InterruptedException e) { 
  16.  
  17.             throw new RuntimeException(e); 
  18.  
  19.         } 
  20.  
  21.         System.out.println("end to start compute. passed " + (System.currentTimeMillis() - t)/1000 + " seconds"); 
  22.  
  23.         return rand.nextInt(1000); 
  24.  
  25.     } 
  26.  
  27.     public static void main(String[] args) throws Exception { 
  28.  
  29.         CompletableFuture<Integer> future = CompletableFuture.supplyAsync(Main::getMoreData); 
  30.  
  31.         Future<Integer> f = future.whenComplete((v, e) -> { 
  32.  
  33.             System.out.println(v); 
  34.  
  35.             System.out.println(e); 
  36.  
  37.         }); 
  38.  
  39.         System.out.println(f.get()); 
  40.  
  41.         System.in.read(); 
  42.  
  43.     } 
  44.  

exceptionally方法返回一个新的CompletableFuture,当原始的CompletableFuture抛出异常的时候,就会触发这个CompletableFuture的计算,调用function计算值,否则如果原始的CompletableFuture正常计算完后,这个新的CompletableFuture也计算完成,它的值和原始的CompletableFuture的计算的值相同。也就是这个exceptionally方法用来处理异常的情况。

结果转换

由于回调风格的实现,我们不必因为等待一个计算完成而阻塞着调用线程,而是告诉CompletableFuture当计算完成的时候请执行某个function。而且我们还可以将这些操作串联起来,或者将CompletableFuture组合起来。

  1. public <U> CompletableFuture<U>  thenApply(Function<? super T,? extends U> fn) 
  2.  
  3. public <U> CompletableFuture<U>  thenApplyAsync(Function<? super T,? extends U> fn) 
  4.  
  5. public <U> CompletableFuture<U>  thenApplyAsync(Function<? super T,? extends U> fn, Executor executor) 

这一组函数的功能是当原来的CompletableFuture计算完后,将结果传递给函数fn,将fn的结果作为新的CompletableFuture计算结果。因此它的功能相当于将CompletableFuture<T>转换成CompletableFuture<U>。

使用例子如下:

  1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     return 100; 
  4.  
  5. }); 
  6.  
  7. CompletableFuture<String> f =  future.thenApplyAsync(i -> i * 10).thenApply(i -> i.toString()); 
  8.  
  9. System.out.println(f.get()); //"1000" 

需要注意的是,这些转换并不是马上执行的,也不会阻塞,而是在前一个stage完成后继续执行。

下面一组方法虽然也返回CompletableFuture对象,但是对象的值和原来的CompletableFuture计算的值不同。当原先的CompletableFuture的值计算完成或者抛出异常的时候,会触发这个CompletableFuture对象的计算,结果由BiFunction参数计算而得。因此这组方法兼有whenComplete和转换的两个功能。

  1. public <U> CompletableFuture<U>     handle(BiFunction<? super T,Throwable,? extends U> fn) 
  2.  
  3. public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn) 
  4.  
  5. public <U> CompletableFuture<U>     handleAsync(BiFunction<? super T,Throwable,? extends U> fn, Executor executor) 

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

纯消费结果

上面的方法是当计算完成的时候,会生成新的计算结果(thenApply, handle),或者返回同样的计算结果(whenComplete,CompletableFuture)。CompletableFuture提供了一种处理结果的方法,只对结果执行Action,而不返回新的计算值,因此计算值为Void:

 

  1. public CompletableFuture<Void>  thenAccept(Consumer<? super T> action
  2.  
  3. public CompletableFuture<Void>  thenAcceptAsync(Consumer<? super T> action
  4.  
  5. public CompletableFuture<Void>  thenAcceptAsync(Consumer<? super T> action, Executor executor) 

看它的参数类型也就明白了,它们是消费型函数式接口Consumer,这个接口只有输入,没有返回值。

 

  1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     return 100; 
  4.  
  5. }); 
  6.  
  7. CompletableFuture<Void> f =  future.thenAccept(System.out::println); 
  8.  
  9. System.out.println(f.get()); 
  10.  
  11. public <U> CompletableFuture<Void>                thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action
  12.  
  13. public <U> CompletableFuture<Void>                thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action
  14.  
  15. public <U> CompletableFuture<Void>                thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor) 
  16.  
  17. public CompletableFuture<Void>  runAfterBoth(CompletionStage<?> other,  Runnable action

thenAcceptBoth以及相关方法提供了类似的功能,当两个CompletionStage都正常完成计算的时候,就会执行提供的action,它用来组合另外一个异步的结果。

runAfterBoth是当两个CompletionStage都正常完成计算的时候,执行一个Runnable,这个Runnable并不使用计算的结果。

例子如下:

  1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     return 100; 
  4.  
  5. }); 
  6.  
  7. CompletableFuture<Void> f =  future.thenAcceptBoth(CompletableFuture.completedFuture(10), (x, y) -> System.out.println(x * y)); 
  8.  
  9. System.out.println(f.get()); 

更彻底地,下面一组方法当计算完成的时候会执行一个Runnable,与thenAccept不同,Runnable并不使用CompletableFuture计算的结果。

  1. public CompletableFuture<Void>  thenRun(Runnable action
  2.  
  3. public CompletableFuture<Void>  thenRunAsync(Runnable action
  4.  
  5. public CompletableFuture<Void>  thenRunAsync(Runnable action,  Executor executor) 

因此先前的CompletableFuture计算的结果被忽略了,这个方法返回CompletableFuture<Void>类型的对象。

  1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     return 100; 
  4.  
  5. }); 
  6.  
  7. CompletableFuture<Void> f =  future.thenRun(() -> System.out.println("finished")); 
  8.  
  9. System.out.println(f.get()); 

因此,你可以根据方法的参数的类型来加速你的记忆。Runnable类型的参数会忽略计算的结果,Consumer是纯消费计算结果,BiConsumer会组合另外一个CompletionStage纯消费,Function会对计算结果做转换,BiFunction会组合另外一个CompletionStage的计算结果做转换。

组合

有时,你需要在一个future结构运行某个函数,但是这个函数也是返回某种future,也就是说是两个future彼此依赖串联在一起,它类似于flatMap。

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

这一组方法接受一个Function作为参数,这个Function的输入是当前的CompletableFuture的计算值,返回结果将是一个新的CompletableFuture,这个新的CompletableFuture会组合原来的CompletableFuture和函数返回的CompletableFuture。因此它的功能类似:

A +--> B +---> C

记住,thenCompose返回的对象并不一是函数fn返回的对象,如果原来的CompletableFuture还没有计算出来,它就会生成一个新的组合后的CompletableFuture。

例子:

  1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     return 100; 
  4.  
  5. }); 
  6.  
  7. CompletableFuture<String> f =  future.thenCompose( i -> { 
  8.  
  9.     return CompletableFuture.supplyAsync(() -> { 
  10.  
  11.         return (i * 10) + ""
  12.  
  13.     }); 
  14.  
  15. }); 
  16.  
  17. System.out.println(f.get()); //1000 

 

而下面的一组方法thenCombine用来复合另外一个CompletionStage的结果。它的功能类似:

A +

  |

  +------> C

  +------^

B +

两个CompletionStage是并行执行的,它们之间并没有先后依赖顺序,other并不会等待先前的CompletableFuture执行完毕后再执行。

  1. public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) 
  2.  
  3. public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn) 
  4.  
  5. public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor) 

其实从功能上来讲,它们的功能更类似thenAcceptBoth,只不过thenAcceptBoth是纯消费,它的函数参数没有返回值,而thenCombine的函数参数fn有返回值。

 

  1. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  2.  
  3.     return 100; 
  4.  
  5. }); 
  6.  
  7. CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { 
  8.  
  9.     return "abc"
  10.  
  11. }); 
  12.  
  13. CompletableFuture<String> f =  future.thenCombine(future2, (x,y) -> y + "-" + x); 
  14.  
  15. System.out.println(f.get()); //abc-100 

Either

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

  1. public CompletableFuture<Void>        acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action
  2.  
  3. public CompletableFuture<Void>        acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action
  4.  
  5. public CompletableFuture<Void>        acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor) 
  6.  
  7. public <U> CompletableFuture<U>     applyToEither(CompletionStage<? extends T> other, Function<? super T,U> fn) 
  8.  
  9. public <U> CompletableFuture<U>     applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn) 
  10.  
  11. public <U> CompletableFuture<U>     applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn, Executor executor) 

acceptEither方法是当任意一个CompletionStage完成的时候,action这个消费者就会被执行。这个方法返回CompletableFuture<Void>

applyToEither方法是当任意一个CompletionStage完成的时候,fn会被执行,它的返回值会当作新的CompletableFuture<U>的计算结果。

下面这个例子有时会输出100,有时候会输出200,哪个Future先完成就会根据它的结果计算。

  1. Random rand = new Random(); 
  2.  
  3. CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { 
  4.  
  5.     try { 
  6.  
  7.         Thread.sleep(10000 + rand.nextInt(1000)); 
  8.  
  9.     } catch (InterruptedException e) { 
  10.  
  11.         e.printStackTrace(); 
  12.  
  13.     } 
  14.  
  15.     return 100; 
  16.  
  17. }); 
  18.  
  19. CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> { 
  20.  
  21.     try { 
  22.  
  23.         Thread.sleep(10000 + rand.nextInt(1000)); 
  24.  
  25.     } catch (InterruptedException e) { 
  26.  
  27.         e.printStackTrace(); 
  28.  
  29.     } 
  30.  
  31.     return 200; 
  32.  
  33. }); 
  34.  
  35. CompletableFuture<String> f =  future.applyToEither(future2,i -> i.toString());  

辅助方法 allOf 和 anyOf

前面我们已经介绍了几个静态方法:completedFuture、runAsync、supplyAsync,下面介绍的这两个方法用来组合多个CompletableFuture。

  1. public static CompletableFuture<Void>  allOf(CompletableFuture<?>... cfs) 
  2.  
  3. public static CompletableFuture<Object>  anyOf(CompletableFuture<?>... cfs) 

allOf方法是当所有的CompletableFuture都执行完后执行计算。

anyOf方法是当任意一个CompletableFuture执行完后就会执行计算,计算的结果相同。

下面的代码运行结果有时是100,有时是"abc"。但是anyOf和applyToEither不同。anyOf接受任意多的CompletableFuture,但是applyToEither只是判断两个CompletableFuture。anyOf返回值的计算结果是参数中其中一个CompletableFuture的计算结果,applyToEither返回值的计算结果却是要经过fn处理的。当然还有静态方法的区别,线程池的选择等。

  1. Random rand = new Random(); 
  2.  
  3. CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> { 
  4.  
  5.     try { 
  6.  
  7.         Thread.sleep(10000 + rand.nextInt(1000)); 
  8.  
  9.     } catch (InterruptedException e) { 
  10.  
  11.         e.printStackTrace(); 
  12.  
  13.     } 
  14.  
  15.     return 100; 
  16.  
  17. }); 
  18.  
  19. CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { 
  20.  
  21.     try { 
  22.  
  23.         Thread.sleep(10000 + rand.nextInt(1000)); 
  24.  
  25.     } catch (InterruptedException e) { 
  26.  
  27.         e.printStackTrace(); 
  28.  
  29.     } 
  30.  
  31.     return "abc"
  32.  
  33. }); 
  34.  
  35. //CompletableFuture<Void> f =  CompletableFuture.allOf(future1,future2); 
  36.  
  37. CompletableFuture<Object> f =  CompletableFuture.anyOf(future1,future2); 
  38.  
  39. System.out.println(f.get()); 

更进一步

Guava的Future类,它的Futures辅助类提供了很多便利方法,用来处理多个Future,而不像Java的CompletableFuture,只提供了allOf、anyOf两个方法。 比如有这样一个需求,将多个CompletableFuture组合成一个CompletableFuture,这个组合后的CompletableFuture的计算结果是个List,它包含前面所有的CompletableFuture的计算结果,guava的Futures.allAsList可以实现这样的功能,但是对于java CompletableFuture,我们需要一些辅助方法:

  1. public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) { 
  2.  
  3.        CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); 
  4.  
  5.        return allDoneFuture.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.<T>toList())); 
  6.  
  7.    } 
  8.  
  9. public static <T> CompletableFuture<Stream<T>> sequence(Stream<CompletableFuture<T>> futures) { 
  10.  
  11.        List<CompletableFuture<T>> futureList = futures.filter(f -> f != null).collect(Collectors.toList()); 
  12.  
  13.        return sequence(futureList); 
  14.  
  15.    } 

或者Java Future转CompletableFuture:

  1.  public static <T> CompletableFuture<T> toCompletable(Future<T> future, Executor executor) { 
  2.     return CompletableFuture.supplyAsync(() -> { 
  3.  
  4.         try { 
  5.  
  6.             return future.get(); 
  7.  
  8.         } catch (InterruptedException | ExecutionException e) { 
  9.  
  10.             throw new RuntimeException(e); 
  11.  
  12.         } 
  13.  
  14.     }, executor); 
  15.  

 

 

责任编辑:庞桂玉 来源: 田心双木的博客
相关推荐

2021-06-06 16:56:49

异步编程Completable

2024-03-06 08:13:33

FutureJDKCallable

2024-01-11 12:14:31

Async线程池任务

2015-06-16 11:06:42

JavaCompletable

2021-02-21 14:35:29

Java 8异步编程

2020-05-29 07:20:00

Java8异步编程源码解读

2021-08-30 19:00:46

静态CompletableCountDownLa

2023-04-13 07:33:31

Java 8编程工具

2021-09-27 13:01:52

线程阻塞排查

2021-03-16 15:12:57

CompletableFuture机制java

2023-07-19 08:03:05

Future异步JDK

2021-03-18 10:12:54

JavaCompletable字符串

2022-07-08 14:14:04

并发编程异步编程

2022-05-31 07:32:19

JDK8API工具

2022-09-06 08:25:13

线程异步任务

2022-05-13 12:34:16

美团开发实践

2021-06-18 08:25:42

Java泛型通配符

2009-06-24 16:50:11

Java内存模型

2011-12-07 14:57:44

JavaNIO

2009-06-11 08:59:35

点赞
收藏

51CTO技术栈公众号