CompletableFuture异步编程实战与陷阱规避
一、为什么需要异步编程?
1. 同步 vs 异步性能对比
| 场景 |
同步调用耗时 |
异步调用耗时 |
提升比例 |
| 3次顺序HTTP请求 |
900ms |
300ms |
300% |
| 数据库查询+文件IO |
450ms |
150ms |
300% |
| 多服务聚合结果 |
1200ms |
400ms |
300% |
2. 回调地狱的演进
userService.getUser(id, user -> {
orderService.getOrders(user, orders -> {
paymentService.getPayments(orders, payments -> {
});
});
});
CompletableFuture.supplyAsync(() -> userService.getUser(id))
.thenCompose(user -> orderService.getOrdersAsync(user))
.thenAccept(orders -> paymentService.processPayments(orders));
二、核心API全解析
1. 创建异步任务
| 方法 |
作用描述 |
线程池控制 |
supplyAsync(Supplier) |
带返回值的异步任务 |
可指定Executor |
runAsync(Runnable) |
无返回值的异步任务 |
默认ForkJoinPool.commonPool() |
completedFuture(T) |
创建已完成的Future |
- |
ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "result";
}, executor);
2. 任务链式组合
| 组合方法 |
作用描述 |
异常处理特性 |
thenApply(Function) |
同步转换结果 |
异常会中断整个链 |
thenCompose(Function) |
异步嵌套Future |
支持异常传播 |
thenCombine(CompletionStage, BiFunction) |
双任务结果合并 |
任一任务异常则中断 |
CompletableFuture