一、异步任务执行与结果处理
-
基础异步调用
通过
supplyAsync异步执行耗时操作(如远程接口调用),避免阻塞主线程:CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { // 模拟支付接口调用(耗时1秒) Thread.sleep(1000); return "支付成功"; }); future.thenAccept(result -> System.out.println("结果:" + result)); future.join();应用场景:日志记录、邮件发送等非核心逻辑的异步处理。
-
链式回调处理
使用
thenApply对结果进行转换,thenAccept消费最终结果:CompletableFuture.supplyAsync(() -> "Hello") .thenApply(s -> s + " World") // 转换为大写 .thenAccept(System.out::println); // 输出结果特点:无阻塞流水线处理,适用于数据加工场景。
二、任务编排与组合
-
并行任务合并结果
使用
thenCombine合并两个异步任务的结果:CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> " World"); task1.thenCombine(task2, (s1, s2) -> s1 + s2) .thenAccept(System.out::println); // 输出 "Hello World"适用场景:多数据源并行查询后合并(如订单+库存信息)。
-
任务依赖链式执行
使用
thenCompose实现任务依赖(如支付成功后更新订单状态):CompletableFuture.supplyAsync(() -> "支付成功") .thenCompose(result -> CompletableFuture.supplyAsync(() -> "更新订单状态为已支付")) .thenAccept(System.out::println);优势:避免回调地狱,代码结构清晰。
三、异常处理与容错
-
异常捕获与恢复
通过
exceptionally处理异常,提供默认值:CompletableFuture.supplyAsync(() -> { if (Math.random() > 0.5) throw new RuntimeException("模拟异常"); return "成功"; }).exceptionally(ex -> "降级结果") .thenAccept(System.out::println);应用:网络请求失败时返回缓存数据。
-
全局异常监控
使用
whenComplete统一处理异常和结果:future.whenComplete((result, ex) -> { if (ex != null) log.error("任务失败", ex); else log.info("任务结果:{}", result); });场景:分布式系统中监控多个异步操作。
四、多任务协调
-
等待所有任务完成
使用
allOf等待多个任务全部完成:CompletableFuture.allOf(task1, task2, task3) .thenRun(() -> System.out.println("所有任务完成"));典型应用:下单时需并行扣减库存、支付、发送通知。
-
任一任务完成即触发
使用
anyOf实现超时控制或备选方案:CompletableFuture.anyOf(task1, task2) .thenAccept(result -> System.out.println("最快结果:" + result));场景:多数据源查询,优先返回最快结果。
五、自定义线程池与资源管理
-
指定线程池执行
避免默认
ForkJoinPool资源竞争,使用独立线程池:ExecutorService executor = Executors.newFixedThreadPool(10); CompletableFuture.runAsync(() -> {/* 耗时任务 */}, executor);优势:隔离高并发任务,防止线程阻塞。
-
超时控制
通过
orTimeout限制任务执行时间:CompletableFuture.supplyAsync(() -> longRunningTask()) .orTimeout(5, TimeUnit.SECONDS) .exceptionally(ex -> "超时处理");应用:防止接口调用长时间阻塞。
六、实际业务场景案例
场景:电商订单处理流程
// 1. 异步支付
CompletableFuture<String> payFuture = CompletableFuture.supplyAsync(() -> paymentService.pay(orderId));
// 2. 支付成功后更新订单状态
CompletableFuture<Order> updateOrder = payFuture.thenCompose(payResult ->
orderService.updateStatus(orderId, "已支付"));
// 3. 并行扣减库存和发送通知
CompletableFuture.allOf(
inventoryService.deductStock(orderId),
notificationService.send(orderId)
).thenRun(() -> log.info("订单处理完成"));
// 4. 统一处理结果
payFuture.thenAccept(result -> {
if (result.contains("成功")) {
updateOrder.thenAccept(order -> log.info("订单更新成功"));
}
}).exceptionally(ex -> {
log.error("支付失败", ex);
return null;
});
特点:链式调用、并行任务、异常处理结合,体现 CompletableFuture 的核心优势。
总结
CompletableFuture 的经典案例覆盖了异步编程的核心需求:
-
非阻塞:通过回调避免线程阻塞
-
编排能力:支持串行、并行、聚合等多种任务流
-
容错机制:异常捕获与降级策略
-
资源控制:自定义线程池与超时管理
这些特性使其成为微服务架构、高并发系统的关键工具。
169万+

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



