Java并发原生工具:异步编程工具 (CompletableFuture)
·
✅ 核心速览:
CompletableFuture 是 Java 8 引入的异步编程工具,它实现了 Future 接口,并提供了强大的函数式组合能力、异步回调、异常处理和多阶段任务编排。在 JDK 21 时代,结合虚拟线程(Virtual Threads),CompletableFuture 已成为构建高并发、响应式、非阻塞应用的核心基础设施。
其核心能力包括:手动完成(complete)、非阻塞回调(thenApply, thenAccept)、任务组合(thenCompose, thenCombine)、并行聚合(allOf, anyOf)和异常处理(exceptionally, handle)。
核心特性与 API 分类
CompletableFuture 的 API 可分为四类:
1. 创建与完成
| 方法 | 说明 |
|---|---|
CompletableFuture.supplyAsync(Supplier<T>) |
异步执行,返回结果 |
CompletableFuture.runAsync(Runnable) |
异步执行,无返回值 |
CompletableFuture.completedFuture(T) |
创建已完成的 CompletableFuture |
complete(T value) / completeExceptionally(Throwable) |
手动完成(可用于测试或协调) |
2. 链式回调(非阻塞)
| 方法 | 说明 |
|---|---|
thenApply(fn) |
转换结果(有返回值) |
thenAccept(consumer) |
消费结果(无返回值) |
thenRun(runnable) |
忽略结果,执行操作 |
thenCompose(fn) |
扁平化组合(用于链式异步调用) |
thenCombine(other, fn) |
合并两个 CompletableFuture 的结果 |
3. 并行聚合
| 方法 | 说明 |
|---|---|
CompletableFuture.allOf(CF...) |
等待所有 CompletableFuture 完成,需通过 join() 获取原始结果 |
CompletableFuture.anyOf(CF...) |
等待任一 CompletableFuture 完成 |
4. 异常处理
| 方法 | 说明 |
|---|---|
exceptionally(fn) |
仅当发生异常时调用 |
handle(biFn) |
总是调用(无论成功或失败) |
whenComplete(action) |
类似 handle,但不改变结果 |
异常处理机制
CompletableFuture 的异常处理遵循传播规则:
- 若中间阶段抛出异常,后续的
thenApply/thenAccept会被跳过。 - 异常会一直向后传递,直到遇到
exceptionally、handle或whenComplete。
最佳实践:在链的末尾使用 handle 统一处理,或在关键节点使用 exceptionally 降级。
使用案例
1. 链式异步调用 (thenCompose)
避免嵌套 CompletableFuture,将其“扁平化”。
// 查询用户 → 查询订单 → 查询商品
CompletableFuture<User> fetchUser = fetchUserAsync(userId);
CompletableFuture<Order> fetchOrder = fetchUser.thenCompose(user ->
fetchOrderAsync(user.getOrderId())
);
CompletableFuture<Product> fetchProduct = fetchOrder.thenCompose(order ->
fetchProductAsync(order.getProductId())
);
Product product = fetchProduct.join(); // 阻塞获取最终结果
2. 并行任务聚合 (allOf)
等待多个独立的异步任务全部完成后,再进行下一步操作。
CompletableFuture<String> future1 = callServiceAAsync();
CompletableFuture<String> future2 = callServiceBAsync();
CompletableFuture<String> future3 = callServiceCAsync();
CompletableFuture<Void> allDone = CompletableFuture.allOf(future1, future2, future3);
allDone.thenRun(() -> {
// allOf 完成后,需要分别调用各 future 的 join/get 来获取结果
String result = future1.join() + future2.join() + future3.join();
System.out.println("聚合结果: " + result);
});
3. 快速失败 (anyOf)
当一个任务完成时立即返回,适用于有多个备选方案的场景(如主备数据库查询)。
CompletableFuture<String> primary = callPrimaryDBAsync();
CompletableFuture<String> backup = callBackupDBAsync();
CompletableFuture<Object> first = CompletableFuture.anyOf(primary, backup);
String result = (String) first.join(); // 返回第一个成功完成的结果
4. 异常降级 (exceptionally)
在主逻辑失败时,提供一个备用的处理逻辑,保证程序的健壮性。
fetchDataAsync()
.exceptionally(ex -> {
log.error("主服务失败", ex);
return fetchFromCache(); // 降级到缓存
})
.thenAccept(data -> process(data));
更多推荐




所有评论(0)