为什么CompletableFuture的回调方法未按照预期顺序执行?
目标
理解CompletableFuture的工作原理。
预期执行逻辑
我最初认为CompletableFuture.runAsync().thenRun().thenRunAsync()的链式调用,会严格按照runAsync() -> thenRun() -> thenRunAsync()的顺序依次执行。
实际运行表现
运行时出现竞态条件,执行顺序不固定,常见的两种执行顺序如下:
runAsync->thenRunAsync+e-> 后续任务runAsync->thenRun-> 后续任务
问题复现代码
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.CompletableFuture; import java.util.concurrent.locks.LockSupport; public class RunExample5 { public static void main(String[] args) { ExecutorService e = Executors.newSingleThreadExecutor(r -> new Thread(r, "sole thread")); CompletableFuture<?> f = CompletableFuture.runAsync(() -> { System.out.println("runAsync:\t" + Thread.currentThread()); LockSupport.parkNanos((int) 1e9); }, e); f.thenRun(() -> System.out.println("thenRun:\t" + Thread.currentThread())); f.thenRunAsync(() -> System.out.println("thenRunAsync:\t" + Thread.currentThread())); f.thenRunAsync(() -> System.out.println("thenRunAsync+e:\t" + Thread.currentThread()), e); LockSupport.parkNanos((int) 2e9); e.shutdown(); } }
问题原因
你看到的执行顺序混乱是回调注册方式错误导致的,和CompletableFuture的回调调度规则一致,不属于异常现象:
- 所有回调都是独立绑定到根实例
f上的,并不是串联关系
你写的f.thenRun、f.thenRunAsync都是直接绑定到f的完成事件上,当f运行结束后,所有已经注册的回调会同时触发,相互之间没有先后依赖,自然不会按你预想的顺序执行。只有写成f.thenRun(...).thenRunAsync(...)的链式结构,让下一个回调绑定在上一个回调的返回CompletableFuture上,才能保证执行顺序。 - 不同回调的调度逻辑不同
thenRun:如果注册时f已经完成,直接在当前注册线程(也就是main线程)执行;如果f还没完成,会在f的执行线程上运行- 无自定义线程池的
thenRunAsync:不管f是否完成,都会把任务提交到JDK默认的公共ForkJoinPool执行 - 带自定义线程池的
thenRunAsync+e:不管f是否完成,都会把任务提交到你传入的单线程池执行
你用的是单线程自定义池,runAsync和thenRunAsync+e都提交到这个池子里排队,其他回调走不同的线程调度,自然就会出现执行顺序不固定的竞态情况。
内容的提问来源于stack exchange,提问作者Jason Rich Darmawan
相关产品推荐
相关产品推荐

