← 中文资源

简体中文版本

CompletableFuture 组合

用 supplyAsync、thenApply 与 thenCompose 串联异步计算,并通过 join 获取最终结果。

阅读英文原文

题目

使用 CompletableFuture 的链式调用组合多个异步操作,并合并结果。参考实现先异步提供 42,经过乘 2 的转换,再用 thenCompose 接入另一个异步加法,最后通过 join 取得结果。

  • 输入契约:需要串联的异步操作。
  • 输出契约:组合后的异步结果。
  • 公开样例:future.thenApply(x -> x*2) 返回转换后的 future。

解题思路

CompletableFuture 用函数式组合替代回调嵌套。supplyAsync 在异步线程中产生值;thenApply 对结果做同步转换,适合普通映射;thenCompose 接收返回另一个 CompletableFuture 的函数,用于把两层 future 展平,避免得到嵌套结构。链式调用只在上一阶段完成后执行,最终用 join 阻塞等待并取回结果。

参考实现要点

  1. CompletableFuture.supplyAsync(() -> 42) 启动异步计算,得到 CompletableFuture<Integer>。
  2. thenApply(x -> x * 2) 把结果映射为 84。
  3. thenCompose(x -> CompletableFuture.supplyAsync(() -> x + 8)) 接入下一段异步计算,并把 future 展平,结果为 92。
  4. 调用 future.join() 等待完成并获取整型结果。
  5. 整个链条保持类型 CompletableFuture<Integer>,中间转换不阻塞调用线程。

常见错误

  • 对返回 future 的函数使用 thenApply,得到嵌套的 CompletableFuture<CompletableFuture<T>>;需要展平时应使用 thenCompose。
  • 使用 get() 而不是 join(),必须处理受检的 InterruptedException 与 ExecutionException,在无需受检异常的链式代码中更繁琐。
  • 忽略异步阶段的异常,join 时抛出 CompletionException 才暴露问题;应为链条补充 exceptionally 或 handle 做降级。

验证方式

运行参考实现,断言最终结果为 92;再分别验证 thenApply 与 thenCompose 的返回类型,确认后者不会产生嵌套 future。可以人为让某个阶段抛出异常,观察 join 的异常行为,并添加 exceptionally 分支验证恢复逻辑。

代码示例

CompletableFuture<Integer> future = CompletableFuture
    .supplyAsync(() -> 42)
    .thenApply(x -> x * 2)
    .thenCompose(x -> CompletableFuture.supplyAsync(() -> x + 8));
int result = future.join();