什么,你还不会用CompletableFuture?

开发 后端
本篇会介绍CompletableFuture的api,并用一些示例演示如何去使用。

[[387949]]

上一篇我们讲了Future机制,有兴趣的可以参考谈谈Future、Callable、FutureTask关系

但Future机制,还不那么灵活,比如怎么去利用Future机制描述两个任务串行执行,又或是两个任务并行执行,又或是只关心最先执行结束的任务结果。

Future机制在一定程度上都无法快速地满足以上需求,CompletableFuture便应运而生了。

本片会介绍CompletableFuture的api,并用一些示例演示如何去使用。

1. 创建一个异步任务

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

supplyAsync与runAsync的区别在于:supplyAsync有返回值,而runAsync没有返回值

带Executor参数的构造函数,则使用线程池中的线程执行异步任务(线程池可以参考说说线程池)

不带Executor参数的构造函数,则使用ForkJoinPool.commonPool()中的线程执行异步任务(Fork/Join框架可以参考谈谈并行流parallelStream)

1.1 示例:使用supplyAsync创建一个有返回值的异步任务

  1. public class Case1 { 
  2.  
  3.     public static void main(String[] args) throws Exception { 
  4.  
  5.         CompletableFuture<Integer> completableFuture=CompletableFuture.supplyAsync(()->{ 
  6.             try { 
  7.                 Thread.sleep(1000); 
  8.             } catch (InterruptedException e) { 
  9.                 e.printStackTrace(); 
  10.             } 
  11.             return 1; 
  12.         }); 
  13.         //该方法会一直阻塞 
  14.         Integer result = completableFuture.get(); 
  15.         System.out.println(result); 
  16.     } 
  17.  

2. 异步任务的回调

  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); 

whenComplete开头的方法在计算任务完成(包括正常完成与出现异常)之后会回调

而exceptionally则只会在计算任务出现异常时才会被回调

如何确定哪个线程去回调whenComplete,比较复杂,先略过。

而回调whenCompleteAsync的线程比较简单,随便拿一个空闲的线程即可,后缀是Async的方法同理。

2.1 示例:计算出现异常,使用whenComplete与exceptionally进行处理

  1. package com.qcy.testCompleteableFuture; 
  2.  
  3. import java.util.concurrent.CompletableFuture; 
  4. import java.util.concurrent.ExecutionException; 
  5. import java.util.function.BiConsumer; 
  6. import java.util.function.Function
  7. import java.util.stream.IntStream; 
  8.  
  9. /** 
  10.  * @author qcy 
  11.  * @create 2020/09/07 17:40:44 
  12.  */ 
  13. public class Case2 { 
  14.  
  15.     public static void main(String[] args) throws Exception { 
  16.  
  17.         CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> { 
  18.             try { 
  19.                 Thread.sleep(1000); 
  20.             } catch (InterruptedException e) { 
  21.                 e.printStackTrace(); 
  22.             } 
  23.             System.out.println("执行supplyAsync的线程:" + Thread.currentThread().getName()); 
  24.             int i = 1 / 0; 
  25.             return 1; 
  26.         }); 
  27.  
  28.         completableFuture.whenComplete(new BiConsumer<Integer, Throwable>() { 
  29.             @Override 
  30.             public void accept(Integer integer, Throwable throwable) { 
  31.                 System.out.println("执行whenComplete的线程:" + Thread.currentThread().getName()); 
  32.                 if (throwable == null) { 
  33.                     System.out.println("计算未出现异常,结果:" + integer); 
  34.                 } 
  35.             } 
  36.         }); 
  37.  
  38.         completableFuture.exceptionally(new Function<Throwable, Integer>() { 
  39.             @Override 
  40.             public Integer apply(Throwable throwable) { 
  41.                 //出现异常时,则返回一个默认值 
  42.                 System.out.println("计算出现异常,信息:" + throwable.getMessage()); 
  43.                 return -1; 
  44.             } 
  45.         }); 
  46.  
  47.         System.out.println(completableFuture.get()); 
  48.     } 
  49.  

输出:

当然,CompletableFuture内的各种方法是支持链式调用与Lambda表达式的,我们进行如下改写:

  1. public static void main(String[] args) throws Exception { 
  2.  
  3.      CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> { 
  4.          try { 
  5.              Thread.sleep(2000); 
  6.          } catch (InterruptedException e) { 
  7.              e.printStackTrace(); 
  8.          } 
  9.          System.out.println("执行supplyAsync的线程:" + Thread.currentThread().getName()); 
  10.          int i = 1 / 0; 
  11.          return 1; 
  12.      }).whenComplete((integer, throwable) -> { 
  13.          System.out.println("执行whenComplete的线程:" + Thread.currentThread().getName()); 
  14.          if (throwable == null) { 
  15.              System.out.println("计算未出现异常,结果:" + integer); 
  16.          } 
  17.      }).exceptionally(throwable -> { 
  18.          //出现异常时,则返回一个默认值 
  19.          System.out.println("计算出现异常,信息:" + throwable.getMessage()); 
  20.          return -1; 
  21.      }); 
  22.  
  23.      System.out.println("计算结果:" + completableFuture.get()); 
  24.  } 

3. 任务串行化执行

  1. public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn); 
  2.  
  3.   public CompletableFuture<Void> thenRun(Runnable action); 
  4.  
  5.   public CompletableFuture<Void> thenAccept(Consumer<? super T> action); 
  6.  
  7.   public <U> CompletableFuture<U> handle(BiFunction<? super T, Throwable, ? extends U> fn); 
  8.  
  9.   public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn); 

thenApply,依赖上一次任务执行的结果,参数中的Function<? super T,? extends U>,T代表上一次任务返回值的类型,U代表当前任务返回值的类型,当上一个任务没有出现异常时,thenApply才会被调用

thenRun,不需要知道上一个任务的返回结果,只是在上一个任务执行完成之后开始执行Runnable

thenAccept,依赖上一次任务的执行结果,因为入参是Consumer,所以不返回任何值。

handle和thenApply相似,不过当上一个任务出现异常时,能够执行handle,却不会去执行thenApply

thenCompose,传入一次任务执行的结果,返回一个新的CompleteableFuture对象

3.1 示例:使用串行化任务分解两数相乘并输出

  1. package com.qcy.testCompleteableFuture; 
  2.  
  3. import java.util.concurrent.CompletableFuture; 
  4.  
  5. /** 
  6.  * @author qcy 
  7.  * @create 2020/09/07 17:40:44 
  8.  */ 
  9. public class Case4 { 
  10.  
  11.     public static void main(String[] args) { 
  12.          
  13.         CompletableFuture.supplyAsync(() -> 2) 
  14.                 .thenApply(num -> num * 3) 
  15.                 .thenAccept(System.out::print); 
  16.     } 
  17.  

很显然,输出为6

3.2 示例:使用串行化任务并且模拟出现异常

  1. package com.qcy.testCompleteableFuture; 
  2.  
  3. import java.util.concurrent.CompletableFuture; 
  4. import java.util.function.BiFunction; 
  5.  
  6. /** 
  7.  * @author qcy 
  8.  * @create 2020/09/07 17:40:44 
  9.  */ 
  10. public class Case4 { 
  11.  
  12.     public static void main(String[] args) { 
  13.  
  14.         CompletableFuture.supplyAsync(() -> 2) 
  15.                 .thenApply(num -> num / 0) 
  16.                 .thenApply(result -> result * 3) 
  17.                 .handle((integer, throwable) -> { 
  18.                     if (throwable == null) { 
  19.                         return integer
  20.                     } else { 
  21.                         throwable.printStackTrace(); 
  22.                         return -1; 
  23.                     } 
  24.                 }).thenAccept(System.out::print); 
  25.     } 
  26.  

最终会输出-1

4. 任务同时执行,且都需要执行完成

  1. public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, 
  2. Function<? super T,? super U,? extends V> fn); 
  3.  
  4.   public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, 
  5. Consumer<? super T, ? super U> action); 
  6.  
  7.   public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other,Runnable action); 
  8.  
  9.   public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs); 

thenCombine,合并两个任务,两个任务可以同时执行,都执行成功后,执行最后的BiFunction操作。其中T代表第一个任务的执行结果类型,U代表第二个任务的执行结果类型,V代表合并的结果类型

thenAcceptBoth,和thenCombine特性用法都极其相似,唯一的区别在于thenAcceptBoth进行一个消费,没有返回值

runAfterBoth,两个任务都执行完成后,但不关心他们的返回结构,然后去执行一个Runnable。

allOf,当所有的任务都执行完成后,返回一个CompletableFuture

4.1 示例:使用thenCombine合并任务

  1. package com.qcy.testCompleteableFuture; 
  2.  
  3. import java.util.concurrent.CompletableFuture; 
  4. import java.util.concurrent.ExecutionException; 
  5.  
  6. /** 
  7.  * @author qcy 
  8.  * @create 2020/09/07 17:40:44 
  9.  */ 
  10. public class Case5 { 
  11.  
  12.     public static void main(String[] args) throws Exception { 
  13.  
  14.         CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> { 
  15.             System.out.println("任务1开始"); 
  16.             try { 
  17.                 Thread.sleep(3000); 
  18.             } catch (InterruptedException e) { 
  19.                 e.printStackTrace(); 
  20.             } 
  21.             System.out.println("任务1结束"); 
  22.             return 2; 
  23.         }); 
  24.  
  25.         CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> { 
  26.             System.out.println("任务2开始"); 
  27.             try { 
  28.                 Thread.sleep(3000); 
  29.             } catch (InterruptedException e) { 
  30.                 e.printStackTrace(); 
  31.             } 
  32.             System.out.println("任务2结束"); 
  33.             return 3; 
  34.         }); 
  35.  
  36.         CompletableFuture<Integer> completableFuture = cf1.thenCombine(cf2, (result1, result2) -> result1 * result2); 
  37.         System.out.println("计算结果:" + completableFuture.get()); 
  38.     } 
  39.  

输出:

可以看到两个任务确实是同时执行的

当然,熟练了之后,直接使用链式操作,代码如下:

  1. package com.qcy.testCompleteableFuture; 
  2.  
  3. import java.util.concurrent.CompletableFuture; 
  4.  
  5. /** 
  6.  * @author qcy 
  7.  * @create 2020/09/07 17:40:44 
  8.  */ 
  9. public class Case6 { 
  10.  
  11.     public static void main(String[] args) throws Exception { 
  12.  
  13.         CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> { 
  14.             System.out.println("任务1开始"); 
  15.             try { 
  16.                 Thread.sleep(3000); 
  17.             } catch (InterruptedException e) { 
  18.                 e.printStackTrace(); 
  19.             } 
  20.             System.out.println("任务1结束"); 
  21.             return 2; 
  22.         }).thenCombine(CompletableFuture.supplyAsync(() -> { 
  23.             System.out.println("任务2开始"); 
  24.             try { 
  25.                 Thread.sleep(2000); 
  26.             } catch (InterruptedException e) { 
  27.                 e.printStackTrace(); 
  28.             } 
  29.             System.out.println("任务2结束"); 
  30.             return 3; 
  31.         }), (result1, result2) -> result1 * result2); 
  32.  
  33.         System.out.println("计算结果:" + completableFuture.get()); 
  34.     } 
  35.  

5. 任务同时执行,且只取最先完成的那个任务

  1. public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn); 
  2.  
  3.    public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action); 
  4.  
  5.    public CompletableFuture<Void> runAfterEither(CompletionStage<?> other,Runnable action); 
  6.  
  7.    public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs); 

applyToEither,最新执行完任务,将其结果执行Function操作,其中T是最先执行完的任务结果类型,U是最后输出的类型

acceptEither,最新执行完的任务,将其结果执行消费操作

runAfterEither,任意一个任务执行完成之后,执行Runnable操作

anyOf,多个任务中,返回最先执行完成的CompletableFuture

5.1 示例:两个任务同时执行,打印最先完成的任务的结果

  1. package com.qcy.testCompleteableFuture; 
  2.  
  3. import java.util.concurrent.CompletableFuture; 
  4.  
  5. /** 
  6.  * @author qcy 
  7.  * @create 2020/09/07 17:40:44 
  8.  */ 
  9. public class Case7 { 
  10.  
  11.     public static void main(String[] args) throws Exception { 
  12.  
  13.         CompletableFuture<Void> completableFuture = CompletableFuture.supplyAsync(() -> { 
  14.             System.out.println("任务1开始"); 
  15.             try { 
  16.                 Thread.sleep(3000); 
  17.             } catch (InterruptedException e) { 
  18.                 e.printStackTrace(); 
  19.             } 
  20.             System.out.println("任务1结束"); 
  21.             return 2; 
  22.         }).acceptEither(CompletableFuture.supplyAsync(() -> { 
  23.             System.out.println("任务2开始"); 
  24.             try { 
  25.                 Thread.sleep(2000); 
  26.             } catch (InterruptedException e) { 
  27.                 e.printStackTrace(); 
  28.             } 
  29.             System.out.println("任务2结束"); 
  30.             return 3; 
  31.         }), result -> System.out.println(result)); 
  32.  
  33.         //等待CompletableFuture返回,防止主线程退出 
  34.         completableFuture.join(); 
  35.     } 
  36.  

输出:

可以看得到,任务2结束后,直接不再执行任务1的剩余代码

5.2 示例:多个任务同时执行,打印最先完成的任务的结果

  1. package com.qcy.testCompleteableFuture; 
  2.  
  3. import java.util.concurrent.CompletableFuture; 
  4.  
  5. /** 
  6.  * @author qcy 
  7.  * @create 2020/09/07 17:40:44 
  8.  */ 
  9. public class Case8 { 
  10.  
  11.     public static void main(String[] args) throws Exception { 
  12.  
  13.         CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(() -> { 
  14.             System.out.println("任务1开始"); 
  15.             try { 
  16.                 Thread.sleep(3000); 
  17.             } catch (InterruptedException e) { 
  18.                 e.printStackTrace(); 
  19.             } 
  20.             System.out.println("任务1结束"); 
  21.             return 2; 
  22.         }); 
  23.  
  24.         CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> { 
  25.             System.out.println("任务2开始"); 
  26.             try { 
  27.                 Thread.sleep(2000); 
  28.             } catch (InterruptedException e) { 
  29.                 e.printStackTrace(); 
  30.             } 
  31.             System.out.println("任务2结束"); 
  32.             return 3; 
  33.         }); 
  34.  
  35.         CompletableFuture<Integer> cf3 = CompletableFuture.supplyAsync(() -> { 
  36.             System.out.println("任务3开始"); 
  37.             try { 
  38.                 Thread.sleep(4000); 
  39.             } catch (InterruptedException e) { 
  40.                 e.printStackTrace(); 
  41.             } 
  42.             System.out.println("任务3结束"); 
  43.             return 4; 
  44.         }); 
  45.  
  46.         CompletableFuture<Object> firstCf = CompletableFuture.anyOf(cf1, cf2, cf3); 
  47.         System.out.println(firstCf.get()); 
  48.     } 
  49.  

输出:

 

责任编辑:姜华 来源: 今日头条
相关推荐

2020-05-14 08:59:28

API网关性能

2022-02-22 08:25:51

typeScript泛型概念泛型使用

2020-09-01 14:17:03

WindowsDefender微软

2020-10-21 10:02:16

架构运维技术

2020-09-27 06:50:56

Java互联网注解

2022-08-01 08:17:46

mysqlwindows系统

2019-09-03 09:30:46

ss 命令SocketLinux

2020-09-15 09:50:47

程序员技能开发者

2020-12-18 09:45:33

DockerLinux命令

2020-08-26 14:40:38

explainMySQL数据库

2020-11-09 09:03:35

高并发多线程ThreadLocal

2012-05-02 15:38:49

金山快盘网盘

2018-09-13 10:40:40

Linux命令find

2020-12-07 09:15:00

JavaScript数组 reduce

2022-08-12 15:58:34

Docker

2019-11-28 16:48:00

华为Mate X

2022-09-09 14:56:18

Linuxcpu

2021-01-28 09:40:33

运维监控工具软件

2021-04-27 14:05:50

数字人民币数字货币区块链

2020-03-10 08:33:04

HTTP演变协议
点赞
收藏

51CTO技术栈公众号