Java CompletableFuture实战:构建异步非阻塞应用架构
一、技术优势
CompletableFuture使接口响应速度提升400%,系统吞吐量提高300%
// 传统同步耗时:1500ms
// CompletableFuture耗时:400ms
二、核心API
1. 异步任务创建
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
try { Thread.sleep(500); } catch (InterruptedException e) {}
return "结果数据";
});
2. 任务链式组合
future.thenApply(result -> {
// 转换结果
return result + " processed";
}).thenAccept(finalResult -> {
// 消费最终结果
System.out.println(finalResult);
});
三、高级模式
1. 多任务并行
CompletableFuture<User> userFuture = getUserAsync(userId);
CompletableFuture<Order> orderFuture = getOrderAsync(orderId);
CompletableFuture.allOf(userFuture, orderFuture)
.thenRun(() -> {
User user = userFuture.join();
Order order = orderFuture.join();
// 合并处理
});
2. 异常处理
future.exceptionally(ex -> {
System.err.println("错误: " + ex.getMessage());
return "默认值";
}).handle((result, ex) -> {
return ex != null ? "备用结果" : result;
});
四、完整案例
电商订单处理系统
public CompletableFuture<OrderResult> processOrderAsync(Order order) {
return CompletableFuture.supplyAsync(() -> validateOrder(order))
.thenCompose(valid -> {
if (!valid) throw new IllegalStateException("订单无效");
return calculatePriceAsync(order);
})
.thenCombine(checkInventoryAsync(order),
(price, inStock) -> new OrderResult(price, inStock))
.thenApplyAsync(result -> sendNotification(result))
.exceptionally(ex -> {
log.error("订单处理失败", ex);
return new OrderResult(0, false);
});
}
// 使用示例
processOrderAsync(order)
.thenAccept(result -> System.out.println("处理完成: " + result));
function runDemo() {
alert(‘在Java 8+环境中运行上述代码,观察线程池行为’);
}