completablefuture声明式异步编排核心是链式调用组合方法表达任务依赖:thenapply/thenaccept/thenrun用于串行处理,thencompose扁平化嵌套异步,thencombine/thenacceptboth并发合并结果,exceptionally/handle统一错误处理。

CompletableFuture 的声明式异步编排,核心在于用链式调用替代手动线程管理,通过 组合方法(如 thenApply、thenCompose、thenCombine)表达任务依赖关系,而不是用 get() 阻塞等待或显式创建线程。
用 thenApply / thenAccept / thenRun 做串行转换与消费
适合“一个任务完成后,对结果做处理”的场景。这些方法返回新的 CompletableFuture,保持异步流不中断。
- thenApply:接收上一阶段结果,返回新值(有返回值,类型可变)
- thenAccept:接收结果,只消费,不返回(void 操作)
- thenRun:不关心前序结果,只执行动作(无参)
示例:
CompletableFuture<string> name = CompletableFuture.completedFuture("Alice");
CompletableFuture<integer> length = name.thenApply(s -> s.length());
CompletableFuture<void> log = length.thenAccept(len -> System.out.println("Length: " + len));
</void></integer></string>
用 thenCompose 处理返回 CompletableFuture 的函数
当你的转换逻辑本身是异步的(即返回另一个 CompletableFuture),必须用 thenCompose,而不是 thenApply —— 否则会得到 CompletableFuture<completablefuture>></completablefuture>,造成嵌套。
它会“扁平化”一层,把两个异步操作自然衔接。
CompletableFuture<string> userId = CompletableFuture.completedFuture("1001");
CompletableFuture<user> user = userId.thenCompose(id ->
CompletableFuture.supplyAsync(() -> fetchUserById(id)) // 返回 CompletableFuture<user>
);
</user></user></string>
用 thenCombine / thenAcceptBoth 并发合并两个独立异步结果
当两个异步任务无依赖、可并行执行,但后续需要它们的结果一起计算时,用这两个方法。
- thenCombine:接收两个结果,返回新值
- thenAcceptBoth:接收两个结果,只消费,不返回
注意:两个源头 CompletableFuture 会真正并发执行,框架自动等待两者完成。
CompletableFuture<double> price = CompletableFuture.supplyAsync(() -> getPrice());
CompletableFuture<integer> stock = CompletableFuture.supplyAsync(() -> getStock());
CompletableFuture<string> info = price.thenCombine(stock, (p, s) ->
String.format("Price: %.2f, Stock: %d", p, s)
);
</string></integer></double>
用 exceptionally / handle 统一错误处理
声明式编排中,异常不应沿调用栈向上抛,而应被异步捕获并转化为可控行为。
- exceptionally:仅在发生异常时提供默认值(类似 try-catch 的 catch)
- handle:无论成功失败都执行,接收结果和异常(更灵活,类似 finally + 分支判断)
示例(容错兜底):
CompletableFuture<string> data = CompletableFuture
.supplyAsync(() -> riskyFetch())
.exceptionally(ex -> {
log.warn("Fetch failed, using fallback", ex);
return "default-data";
});
</string>Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











