一、CompletableFuture 核心原理
底层原理:内部维护状态机(三种终态:Completed任务成功完成并包含结果、Cancelled任务被显式取消、Exceptionally任务执行过程中抛出异常)、CAS操作、ForkJoinPool任务调度,并通过Completion对象链式管理依赖对象。状态字段使用位运算,通过volatile保证可见性,status字段标识任务状态。
核心功能包括:支持异步链式调用(如 thenApply、thenAccept),将多个异步操作串联;提供 thenCombine、allOf、anyOf 等组合方法,合并多个 CompletableFuture 的结果;通过 exceptionally 或 handle 捕获并处理异常;支持手动完成(complete)或异常终止(completeExceptionally)任务。
1.1 状态机设计
Incomplete
Completed:
complete()
Cancelled:
cancel()
Exceptionally:
completeExceptionally()
CompletableFuture 内部维护一个状态机,包含三种终态:
- Completed:任务成功完成并包含结果
- Cancelled:任务被显式取消
- Exceptionally:任务执行过程中抛出异常
1.2 依赖链存储机制
当多个操作链式组合时,CompletableFuture 使用栈结构存储依赖关系:
future.thenApply(func1)
.thenApply(func2)
.thenAccept(consumer);
执行流程:
- 原始任务完成时触发栈顶操作
- 每个操作执行后生成新阶段
- 新阶段完成后触发下一依赖
- 异常沿调用链传播直到被捕获
二、核心操作全解
2.1 任务创建
无返回值任务:
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("后台任务执行中...");
// 模拟耗时操作
Thread.sleep(1000);
});
有返回值任务:
CompletableFuture<String> dataFuture = CompletableFuture.supplyAsync(() -> {
return fetchDataFromRemote(); // 返回数据
});
2.2 结果转换
同步转换 (thenApply):
dataFuture.thenApply(rawData -> {
// 在当前线程立即执行转换
return parseData(rawData);
});
异步转换 (thenApplyAsync):
CompletableFuture<Report> reportFuture = dataFuture.thenApplyAsync(rawData -> {
// 在独立线程执行耗时转换
return generateReport(rawData);
}, reportThreadPool);
2.3 任务组合
链式组合 (thenCompose):
CompletableFuture<User> userFuture = getUserProfile()
.thenCompose(pro
CompletableFuture原理与实战

最低0.47元/天 解锁文章
606

被折叠的 条评论
为什么被折叠?



