一、基本概念
CompletableFuture 是 Java 8 引入的异步编程工具,它实现了 Future 和 CompletionStage 接口,提供了强大的异步编程能力:
- 异步执行:非阻塞式任务执行
- 链式调用:支持多个异步操作的流水线处理
- 组合操作:可以组合多个 Future 的结果
- 异常处理:内置完善的异常处理机制
二、核心方法
1. 创建 CompletableFuture
// 创建已完成Future
CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("Result");
// 创建异步任务(无返回值)
CompletableFuture<Void> runAsyncFuture = CompletableFuture.runAsync(() -> {
System.out.println("Running async task");
});
// 创建异步任务(有返回值)
CompletableFuture<String> supplyAsyncFuture = CompletableFuture.supplyAsync(() -> {
return "Async result";
});
2. 结果处理
// thenApply - 转换结果
CompletableFuture<Integer> lengthFuture = supplyAsyncFuture.thenApply(s -> s.length());
// thenAccept - 消费结果
supplyAsyncFuture.thenAccept(result -> System.out.println("Result: " + result));
// thenRun - 结果无关操作
supplyAsyncFuture.thenRun(() -> System.out.println("Task completed"));
3. 组合操作
// thenCompose - 扁平化组合
CompletableFuture<String> composedFuture = supplyAsyncFuture.thenCompose(s ->
CompletableFuture.supplyAsync(() -> s + " composed"));
// thenCombine - 合并两个Future结果
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (s1, s2) -> s1 + " " + s2);
4. 多任务处理
// allOf - 等待所有完成
CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2);
// anyOf - 任一完成即可
CompletableFuture<Object> anyFuture = CompletableFuture.anyOf(future1, future2);
三、异常处理
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) {
throw new RuntimeException("Error occurred");
}
return "Success";
})
.exceptionally(ex -> {
System.out.println("Exception: " + ex.getMessage());
return "Fallback value";
})
.handle((result, ex) -> {
if (ex != null) {
return "Handled error";
}
return result;
});
四、线程池控制
ExecutorService customExecutor = Executors.newFixedThreadPool(5);
CompletableFuture.supplyAsync(() -> {
// 耗时操作
return "Result with custom executor";
}, customExecutor);
五、实用技巧
- 超时控制 (Java 9+)
future.orTimeout(1, TimeUnit.SECONDS)
.exceptionally(ex -> "Timeout occurred");
- 完成时回调
future.whenComplete((result, ex) -> {
if (ex != null) {
System.out.println("Exception: " + ex);
} else {
System.out.println("Result: " + result);
}
});
- 手动完成
CompletableFuture<String> manualFuture = new CompletableFuture<>();
manualFuture.complete("Manual result");
// 或
manualFuture.completeExceptionally(new RuntimeException());
六、典型应用场景
- 并行IO操作:同时发起多个网络请求
- 流水线处理:多个步骤的异步处理流程
- 超时控制:为异步操作设置超时
- 结果聚合:合并多个异步操作的结果
- 回退机制:主操作失败时使用备用方案
七、注意事项
- 避免在回调中执行阻塞操作
- 合理控制线程池大小
- 注意异常传播机制
- 考虑使用超时控制防止无限等待
- 避免回调地狱,保持代码可读性
CompletableFuture 提供了比传统 Future 更强大的异步编程能力,合理使用可以显著提高系统吞吐量和响应速度。

640

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



