Java 并发编程进阶:CompletableFuture 异步编程最佳实践
Java 并发编程进阶:CompletableFuture 异步编程最佳实践
CompletableFuture 是 Java 8 引入的强大异步编程工具,它实现了 Future 接口并支持流式调用。本文整理一些比较实用的用法,帮助你构建更稳的异步代码。
一、CompletableFuture 基础
1.1 创建异步任务
// 方式一:supplyAsync 有返回值
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Hello Async";
});
// 方式二:runAsync 无返回值
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Running async");
});
1.2 thenApply vs thenApplyAsync
// thenApply:使用同一线程执行
CompletableFuture<String> result = future.thenApply(s -> s + " World");
// thenApplyAsync:使用新线程执行(推荐)
CompletableFuture<String> result = future.thenApplyAsync(s -> s + " World");
二、组合异步任务
2.1 thenCompose 串联
CompletableFuture<String> f1 = CompletableFuture
.supplyAsync(() -> fetchUser())
.thenCompose(user -> CompletableFuture.supplyAsync(() -> fetchOrders(user)));
2.2 thenCombine 并行
CompletableFuture<User> userFuture = CompletableFuture.supplyAsync(this::getUser);
CompletableFuture<Order> orderFuture = CompletableFuture.supplyAsync(this::getOrder);
CompletableFuture<Result> result = userFuture
.thenCombine(orderFuture, User::combineWidthOrder);
三、异常处理
3.1 exceptionally
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> riskyOperation())
.exceptionally(ex -> {
log.error("Error: " + ex.getMessage());
return "Default Value";
});
3.2 handle - 无论成功失败都处理
CompletableFuture<String> future = future
.handle((result, ex) -> {
if (ex != null) {
return "Error: " + ex.getMessage();
}
return result;
});
四、最佳实践
- 使用自定义线程池:避免使用默认的 ForkJoinPool
- 合理使用 thenApplyAsync:充分利用线程资源
- 做好异常处理:使用 handle 捕获所有异常
- 避免 CompletableFuture 嵌套:用 thenCompose 替代
想了解更多并发编程内容?可以查看我的系列文章《Java 并发编程实战》
祝编码愉快!

浙公网安备 33010602011771号