CompletableFuture接口说明
CompletableFuture是Future的子类,接口Future接口虽然实现了异步调用,但是存在一个问题,为了判断线程是否已完成计算,或者要获取计算结果,我们需要不断的轮询,通过循环调用Future的isDone方法或者是直接调用get的方法阻塞线程。
在JDK8中,提供了CompletableFuture类来解决这类问题,它可以在线程完成计算后用when、then等方式调用我们定义后续处理方法,省去了轮询的操作(笔者最近在读RocketMQ源码,发现在Broker上使用了CompletableFuture类,因此打算记录一下基本功能和用法,希望后续有时间能详细研读一下实现源码。)
CompletableFuture有以下几种构造方式:
//没有计算过程,直接返回计算结果
CompletableFuture<String>futureNoComplete=CompletableFuture.completedFuture("hello world");
//没有返回值的异步计算
CompletableFuture<Void>futureNoReturnNoExecutor=CompletableFuture.runAsync(()->doSomething());
CompletableFuture<Void>futureNoReturnWithExecutor=CompletableFuture.runAsync(()->doSomething(), Executors.newSingleThreadExecutor());
//带返回值的异步计算
CompletableFuture<String> futureWithReturnNoExector=CompletableFuture.supplyAsync(()->doSomethingReturnString());
CompletableFuture<String> futureWithReturnWithExecutor=CompletableFuture.supplyAsync(()->doSomethingReturnString(), Executors.newSingleThreadExecutor());
当completeFuture代表的任务完成了,可以使用一系列的函数接口来定义当前Future完成后的后续计算。
//执行完当前任务后,以当前任务的返回值作为fn任务的输入,并返回计算结果
public <U> CompletableFuture<U> thenApply(
Function<? super T,? extends U> fn) {
return uniApplyStage(null, fn);
}
//执行完当前任务后,将返回值作为输入,计算fn任务,并返回结果
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn) {
return uniApplyStage(asyncPool, fn);
}
//执行完当前任务后,以当前任务返回值作为输入,并返回计算结果,该计算过程使用executor中的不同线程来执行
public <U> CompletableFuture<U> thenApplyAsync(
Function<? super T,? extends U> fn, Executor executor) {
return uniApplyStage(screenExecutor(executor), fn);
}
//执行完当前任务后,将返回值作为action任务的输入参数进行计算
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
return uniAcceptStage(null, action);
}
//执行完当前任务后,将返回值作为action任务的输入参数进行计算
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
return uniAcceptStage(asyncPool, action);
}
//执行完当前任务后,将返回值作为action任务的输入参数进行计算
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
Executor executor) {
return uniAcceptStage(screenExecutor(executor), action);
}
//执行完当前任务后ÿ