一、CompletableFuture使用详解
简单的任务,用Future获取结果还好,但我们并行提交的多个异步任务,往往并不是独立的,很多时候业务逻辑处理存在串行[依赖]、并行、聚合的关系。如果要我们手动用 Fueture 实现,是非常麻烦的。
CompletableFuture是Future接口的扩展和增强。CompletableFuture实现了Future接口,并在此基础上进行了丰富地扩展,完美地弥补了Future上述的种种问题。更为重要的是,CompletableFuture实现了对任务的编排能力。借助这项能力,我们可以轻松地组织不同任务的运行顺序、规则以及方式。从某种程度上说,这项能力是它的核心能力。而在以往,虽然通过CountDownLatch等工具类也可以实现任务的编排,但需要复杂的逻辑处理,不仅耗费精力且难以维护。
jdk8 API文档:docs.oracle.com/javase/8/do…
CompletionStage接口: 执行某一个阶段,可向下执行后续阶段。异步执行,默认线程池是ForkJoinPool.commonPool()
在使用completableFuture的时候,最好创建自己业务的单独线程池,否则会使用默认的线程池,这样如果业务比较多,可能会有一些问题。
1-1、应用场景
描述依赖关系:
- thenApply() 把前面异步任务的结果,交给后面的Function
- thenCompose()用来连接两个有依赖关系的任务,结果由第二个任务返回
描述and聚合关系:
- thenCombine:任务合并,有返回值
- thenAccepetBoth:两个任务执行完成后,将结果交给thenAccepetBoth消耗,无返回值。
- runAfterBoth:两个任务都执行完成后,执行下一步操作(Runnable)。
描述or聚合关系:
- applyToEither:两个任务谁执行的快,就使用那一个结果,有返回值。
- acceptEither: 两个任务谁执行的快,就消耗那一个结果,无返回值。
- runAfterEither: 任意一个任务执行完成,进行下一步操作(Runnable)。
并行执行:
CompletableFuture类自己也提供了anyOf()和allOf()用于支持多个CompletableFuture并行执行
1-2、创建异步操作
CompletableFuture 提供了四个静态方法来创建一个异步操作:
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
这四个方法区别在于:
- runAsync 方法以Runnable函数式接口类型为参数,没有返回结果,supplyAsync 方法Supplier函数式接口类型为参数,返回结果类型为U;
Supplier 接口的 get() 方法是有返回值的(会阻塞) 没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。- 默认情况下 CompletableFuture 会使用公共的 ForkJoinPool 线程池,这个线程池默认创建的线程数是 CPU 的核数(也可以通过 JVM option:-Djava.util.concurrent.ForkJoinPool.common.parallelism 来设置 ForkJoinPool 线程池的线程数)。如果所有 CompletableFuture 共享一个线程池,那么一旦有任务执行一些很慢的 I/O 操作,就会导致线程池中所有线程都阻塞在 I/O 操作上,从而造成线程饥饿,进而影响整个系统的性能。所以,
强烈建议要根据不同的业务类型创建不同的线程池,以避免互相干扰
1-2-1、runAsync&supplyAsync
public class CompletableFutureDemo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Runnable runnable = () -> System.out.println("执行无返回结果的异步任务");
CompletableFuture.runAsync(runnable);
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("执行有返回值的异步任务");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello World";
});
String result = future.get();
System.out.println(result);
}
}
执行结果:
1-2-2、获取结果
join&get
join()和get()方法都是用来获取CompletableFuture异步之后的返回值。join()方法抛出的是uncheck异常(即未经检查的异常),不会强制开发者抛出。get()方法抛出的是经过检查的异常,ExecutionException, InterruptedException 需要用户手动处理(抛出或者 try catch)
1-3、结果处理
通过whenComplete,我们就可以自动获取CompleTableFuture.supplyAsync执行的结果,在业务场景中:比如用户下单成功返回,之后我们就可以通过supplyAsync获取下单的结果,进行给用户增加积分的操作。
当CompletableFuture的计算结果完成,或者抛出异常的时候,我们可以执行特定的 Action。主要是下面的方法:
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 CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
- Action的类型是BiConsumer,它可以处理正常的计算结果,或者异常情况。
- 方法不以Async结尾,意味着Action使用相同的线程执行,而
Async可能会使用其它的线程去执行(如果使用相同的线程池,也可能会被同一个线程选中执行)。 - 这几个方法都会返回CompletableFuture,当Action执行完毕后它的结果返回原始的CompletableFuture的计算结果或者返回异常
1-3-1、whenComplete&exceptionally
首先通过CompletableFuture.supplyAsync创建了一个异步操作(操作中通过随机数制造一个空指针异常),然后下面通过whenComplete来获得结果处理
需要注意的是
-
whenComplete传入了new BiConsumer其是一个消费类型的接口,因此在调用whenComplete的时候不用再get/join; -
exceptionally传入了一个Function,不是消费类型,因此需要通过get/join来获取结果
public class CompletableFutureDemo02 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
if (new Random().nextInt(10) % 2 == 0) {
int i = 12 / 0;
}
System.out.println("执行结束!");
return "test";
});
future.whenComplete(new BiConsumer<String, Throwable>() {
@Override
public void accept(String t, Throwable action) {
System.out.println(t+" 执行完成!");
}
});
future.exceptionally(new Function<Throwable, String>() {
@Override
public String apply(Throwable t) {
System.out.println("执行失败:" + t.getMessage());
return "异常xxxx";
}
}).join();
}
执行结果:
1-4、结果转换
所谓结果转换,就是将上一段任务的执行结果作为下一阶段任务的入参参与重新计算,产生新的结果。
1-4-1、thenApply
thenApply 接收一个函数作为参数,使用该函数处理上一个CompletableFuture 调用的结果,并返回一个具有处理结果的Future对象。
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
1-4-1-1、示例
public class CompletableFutureDemo03 {
public static void main(String[] args) {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
int result = 100;
System.out.println("一阶段:" + result);
return result;
}).thenApply(number -> {
int result = number * 3;
System.out.println("二阶段:" + result);
return result;
});
}
}
执行结果:
1-4-2、thenCompose
thenCompose 的参数为一个返回 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)
1-4-2-1、示例
通过thencompose可以将上一个执行结果传入当前方法,并且生成了一个新的CompletableFuture
public class Demo04_thenCompose {
public static void main(String[] args) {
CompletableFuture<Integer> completableFuture=CompletableFuture.supplyAsync(()->{
int number = new Random().nextInt(30);
System.out.println("第一阶段:" + number);
return number;
}).thenCompose(param -> CompletableFuture.supplyAsync(()->{
System.out.println("第二阶段:"+(param*3));
return param*3;
}));
Integer number = completableFuture.join();
System.out.println("计算结果:"+number);
}
}
执行结果:
1-4-3、thenApply 和 thenCompose的区别
- thenApply 转换的是泛型中的类型,返回的是同一个CompletableFuture;
- thenCompose 将内部的 CompletableFuture 调用展开,并使用上一个CompletableFutre 调用的结果在下一步的 CompletableFuture 调用中进行运算,是生成一个新的CompletableFuture。
1-4-3-1、示例
CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> 100).
thenApply(num -> num + " to String");
CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> 100).
thenCompose(num -> CompletableFuture.supplyAsync(() -> num + " to String"));
System.out.println(f1.join()); // 100 to String
System.out.println(f2.join()); // 100 to String
例子中,thApply和thenCompose都是将一个CompletableFuture<Integer>转换为CompletableFuture<String>。不同的是,thenApply中的传入函数的返回值是String,而thenCompose的传入函数的返回值是CompletableFuture<String>。
执行结果:
1-5、结果消费
与结果处理和结果转换系列函数返回一个新的 CompletableFuture 不同,结果消费系列函数只对结果执行Action,而不返回新的计算值。
根据对结果的处理方式,结果消费函数又分为:
- thenAccept系列:对单个结果进行消费
- thenAcceptBoth系列:对两个结果进行消费
- thenRun系列:不关心结果,只对结果执行Action
1-5-1、thenAccept
通过观察该系列函数的参数类型可知,它们是函数式接口Consumer,这个接口只有输入,没有返回值。
thenAccept会在上一节点CompletableFuture计算完成的时候执行一个Runnable,并且会使用上一个CompletableFuture的结果
public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
1-5-1-1、示例
public class Demo05_thenAccept {
public static void main(String[] args) {
CompletableFuture<Void> future = CompletableFuture
.supplyAsync(() -> {
int number = new Random().nextInt(10);
System.out.println("第一阶段:" + number);
return number;
}).thenAccept(number ->
System.out.println("第二阶段:" + number * 5));
}
}
执行结果:
1-5-2、thenAcceptBoth
thenAcceptBoth 函数的作用是,当两个 CompletionStage 都正常完成计算的时候,就会执行提供的action消费两个异步的结果。
public <U> CompletionStage<Void> thenAcceptBoth(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
public <U> CompletionStage<Void> thenAcceptBothAsync(CompletionStage<? extends U> other,BiConsumer<? super T, ? super U> action);
1-5-2-1、示例
public class Demo06_thenAcceptBoth {
public static void main(String[] args) {
CompletableFuture<Integer> future1=CompletableFuture.supplyAsync(()->{
int number = new Random().nextInt(10);
System.out.println("第一阶段:" + number);
return number;
});
CompletableFuture<Integer> future2=CompletableFuture.supplyAsync(()->{
int number = new Random().nextInt(10);
System.out.println("第二阶段:" + number);
return number;
});
future1.thenAcceptBoth(future2,(f1,f2)->{
System.out.println("第三阶段:"+(f1+f2));
});
}
}
执行结果:
1-5-3、thenRun
thenRun 也是对线程任务结果的一种消费函数,与thenAccept不同的是,thenRun 会在上一阶段 CompletableFuture 计算完成的时候执行一个Runnable,Runnable并不使用该 CompletableFuture 计算的结果。
public CompletionStage<Void> thenRun(Runnable action); public CompletionStage<Void> thenRunAsync(Runnable action);
1-5-3-1、示例
public class Demo07_thenRun {
public static void main(String[] args) {
CompletableFuture future1=CompletableFuture.supplyAsync(()->{
Integer number= new Random().nextInt(10);
System.out.println("第一阶段:"+number);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return number;
}).thenRun(()->{
System.out.println("第二阶段执行");
});
future1.join();
}
}
执行结果:
1-6、结果组合
1-6-1、thenCombine
thenCombine 方法,合并两个线程任务的结果,并进一步处理。
public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
1-6-1-1、示例
@Slf4j
public class Demo08_thenCombine {
public static void main(String[] args) {
log.info("张三,进入餐厅,点了一份西红柿鸡蛋炒饭");
CompletableFuture<String> future1=CompletableFuture.supplyAsync(()->{
log.info("厨师炒菜");
sleep(2,TimeUnit.SECONDS);
return "西红柿鸡蛋炒好了";
}).thenCombine(CompletableFuture.supplyAsync(()->{
log.info("服务员蒸米饭");
sleep(3,TimeUnit.SECONDS);
return "米饭好了";
}),(dish,rice)->{
log.info("服务员打饭");
return dish+","+rice;
});
log.info("张三玩王者");
log.info("张三开吃"+future1.join());
}
static void sleep(int t,TimeUnit u){
try {
u.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
执行结果:
1-7、任务交互
所谓线程交互,是指将两个线程任务获取结果的速度相比较,按一定的规则进行下一步处理。
1-7-1、applyToEither
两个线程任务相比较,返回最快执行完的结果。最快返回后,其他线程依然会继续执行。
public <U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other,Function<? super T, U> fn);
public <U> CompletionStage<U> applyToEitherAsync(CompletionStage<? extends T> other,Function<? super T, U> fn);
1-7-1-1、示例
public class Demo09_applyToEither {
public static void main(String[] args) {
CompletableFuture future1=CompletableFuture.supplyAsync(()->{
int number = new Random().nextInt(10);
System.out.println("第一阶段start:" + number);
try {
TimeUnit.SECONDS.sleep(number);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第一阶段end:" + number);
return number;
});
CompletableFuture future2=CompletableFuture.supplyAsync(()->{
int number = new Random().nextInt(10);
System.out.println("第二阶段start:" + number);
try {
TimeUnit.SECONDS.sleep(number);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("第二阶段end:" + number);
return number;
});
future1.applyToEither(future2, new Function() {
@Override
public Object apply(Object o) {
System.out.println("最快执行结果:"+o);
return o;
}
});
future1.join();
future2.join();
}
}
执行结果:
1-7-2、acceptEither
两个线程任务相比较,先获得执行结果的,就对该结果进行下一步的消费操作,另外一个线程继续执行。
public CompletionStage<Void> acceptEither(CompletionStage<? extends T> other,Consumer<? super T> action);
public CompletionStage<Void> acceptEitherAsync(CompletionStage<? extends T> other,Consumer<? super T> action);
1-7-2-1、示例
public class Demo10_acceptEither {
public static void main(String[] args) {
CompletableFuture future1=CompletableFuture.supplyAsync(()->{
int num=new Random().nextInt(10);
sleep(num);
System.out.println("第一执行:"+num);
return num;
});
CompletableFuture future2=CompletableFuture.supplyAsync(()->{
int num=new Random().nextInt(10);
sleep(num);
System.out.println("第二执行:"+num);
return num;
});
future1.acceptEither(future2,(result)->{
System.out.println("最快执行:"+result);
});
future1.join();
future2.join();
}
static void sleep(int time){
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
执行结果:
1-7-3、runAfterEither
两个线程任务相比较,有任何一个执行完成,就进行下一步操作,不关心运行结果。
public CompletionStage<Void> runAfterEither(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterEitherAsync(CompletionStage<?> other,Runnable action);
1-7-3-1、示例
public class Demo11_runAfterEither {
public static void main(String[] args) {
CompletableFuture future1=CompletableFuture.supplyAsync(()->{
int num=new Random().nextInt(10);
sleep(num);
System.out.println("第一执行:"+num);
return num;
});
CompletableFuture future2=CompletableFuture.supplyAsync(()->{
int num=new Random().nextInt(10);
sleep(num);
System.out.println("第二执行:"+num);
return num;
});
future1.runAfterEither(future2,()->{
System.out.println("已经有任务执行完毕");
}).join();
future1.join();
future2.join();
}
static void sleep(int time){
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
执行结果:
1-7-4、runAfterBoth
两个线程任务相比较,两个全部执行完成,才进行下一步操作,不关心运行结果。
public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);
1-7-4-1、示例
public class Demo12_runAfterBoth {
public static void main(String[] args) {
CompletableFuture future1=CompletableFuture.supplyAsync(()->{
int num =new Random().nextInt(10);
SleepUtil.sleep(num);
System.out.println("第一次执行:"+num);
return num;
});
CompletableFuture future2=CompletableFuture.supplyAsync(()->{
int num =new Random().nextInt(10);
SleepUtil.sleep(num);
System.out.println("第二次执行:"+num);
return num;
});
future1.runAfterBoth(future2,()->{
System.out.println("全部执行完毕");
}).join();
future1.join();
future2.join();
}
}
执行结果:
1-7-5、anyOf
anyOf 方法的参数是多个给定的 CompletableFuture,当其中的任何一个完成时,方法返回这个 CompletableFuture。
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
1-7-5-1、示例
public class Demo13_anyOf {
public static void main(String[] args) {
CompletableFuture future1=CompletableFuture.supplyAsync(()->{
int num =new Random().nextInt(10);
SleepUtil.sleep(num);
System.out.println("第一次执行:"+num);
return num;
});
CompletableFuture future2=CompletableFuture.supplyAsync(()->{
int num =new Random().nextInt(10);
SleepUtil.sleep(num);
System.out.println("第二次执行:"+num);
return num;
});
CompletableFuture<Object> result = CompletableFuture.anyOf(future1, future2);
Object fina = result.join();
System.out.println("finally:"+fina);
}
}
执行结果:
1-7-6、allOf
allOf方法用来实现多 CompletableFuture 的同时返回。
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
1-7-6-1、示例
public class Demo14_allOf {
public static void main(String[] args) {
CompletableFuture future1=CompletableFuture.supplyAsync(()->{
int num =new Random().nextInt(10);
SleepUtil.sleep(num);
System.out.println("第一次执行:"+num);
return num;
});
CompletableFuture future2=CompletableFuture.supplyAsync(()->{
int num =new Random().nextInt(10);
SleepUtil.sleep(num);
System.out.println("第二次执行:"+num);
return num;
});
CompletableFuture<Void> all = CompletableFuture.allOf(future1, future2);
System.out.println("等待执行");
all.join();
System.out.println("全部执行完成");
}
}
执行结果:
二、CompletableFuture常用方法小结
通过以上举例使用了一些常用的CompletableFuture的常用方法,下面进行综合对比一下
2-1、使用案例:实现最优的“烧水泡茶”程序
介绍一个泡茶水的例子:
对于烧水泡茶这个程序,一种最优的分工方案:用两个线程 T1 和 T2 来完成烧水泡茶程序,T1 负责洗水壶、烧开水、泡茶这三道工序,T2 负责洗茶壶、洗茶杯、拿茶叶三道工序,其中 T1 在执行泡茶这道工序时需要等待 T2 完成拿茶叶的工序。
2-1-1、基于Future实现
public class FutureTaskDemo3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建任务T2的FutureTask
FutureTask<String> ft2 = new FutureTask<>(new T2Task());
// 创建任务T1的FutureTask
FutureTask<String> ft1 = new FutureTask<>(new T1Task(ft2));
// 线程T1执行任务ft1
Thread T1 = new Thread(ft1);
T1.start();
// 线程T2执行任务ft2
Thread T2 = new Thread(ft2);
T2.start();
// 等待线程T1执行结果
System.out.println(ft1.get());
}
}
// T1Task需要执行的任务:
// 洗水壶、烧开水、泡茶
class T1Task implements Callable<String> {
FutureTask<String> ft2;
// T1任务需要T2任务的FutureTask
T1Task(FutureTask<String> ft2){
this.ft2 = ft2;
}
@Override
public String call() throws Exception {
System.out.println("T1:洗水壶...");
TimeUnit.SECONDS.sleep(1);
System.out.println("T1:烧开水...");
TimeUnit.SECONDS.sleep(15);
// 获取T2线程的茶叶
String tf = ft2.get();
System.out.println("T1:拿到茶叶:"+tf);
System.out.println("T1:泡茶...");
return "上茶:" + tf;
}
}
// T2Task需要执行的任务:
// 洗茶壶、洗茶杯、拿茶叶
class T2Task implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("T2:洗茶壶...");
TimeUnit.SECONDS.sleep(1);
System.out.println("T2:洗茶杯...");
TimeUnit.SECONDS.sleep(2);
System.out.println("T2:拿茶叶...");
TimeUnit.SECONDS.sleep(1);
return "龙井";
}
}
2-1-2、基于CompletableFuture实现
public class CompletableFutureDemo2 {
public static void main(String[] args) {
//任务1:洗水壶->烧开水
CompletableFuture<Void> f1 = CompletableFuture
.runAsync(() -> {
System.out.println("T1:洗水壶...");
sleep(1, TimeUnit.SECONDS);
System.out.println("T1:烧开水...");
sleep(15, TimeUnit.SECONDS);
});
//任务2:洗茶壶->洗茶杯->拿茶叶
CompletableFuture<String> f2 = CompletableFuture
.supplyAsync(() -> {
System.out.println("T2:洗茶壶...");
sleep(1, TimeUnit.SECONDS);
System.out.println("T2:洗茶杯...");
sleep(2, TimeUnit.SECONDS);
System.out.println("T2:拿茶叶...");
sleep(1, TimeUnit.SECONDS);
return "龙井";
});
//任务3:任务1和任务2完成后执行:泡茶
CompletableFuture<String> f3 = f1.thenCombine(f2, (__, tf) -> {
System.out.println("T1:拿到茶叶:" + tf);
System.out.println("T1:泡茶...");
return "上茶:" + tf;
});
//等待任务3执行结果
System.out.println(f3.join());
}
static void sleep(int t, TimeUnit u){
try {
u.sleep(t);
} catch (InterruptedException e) {
}
}
}