CompletableFuture 实战:Java 异步编程高性能实战指南
<h2>前言</h2><p>在高并发场景下,同步阻塞是性能杀手。Java 8 引入的 <strong>CompletableFuture</strong> 彻底改变了异步编程的写法。</p>
<h2>一、为什么需要 CompletableFuture?</h2>
<p>传统 Future 的痛点:</p>
<ul>
<li>future.get() 会阻塞当前线程</li>
<li>无法链式组合多个异步任务</li>
<li>异常处理繁琐</li>
</ul>
<h2>二、基础用法</h2>
<pre><code>CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(1000); } catch (InterruptedException e) { }
return "查询结果";
});</code></pre>
<h2>三、实战场景</h2>
<p>电商首页需要同时查询用户信息、商品推荐、优惠券列表。串行查询耗时 650ms,并行只需 300ms。</p>
<pre><code>@Service
public class HomePageService {
private final ExecutorService executor = Executors.newFixedThreadPool(20);
public HomePageVO buildHomePage(Long userId) {
CompletableFuture<UserInfo> userFuture = CompletableFuture
.supplyAsync(() -> userService.getUserInfo(userId), executor);
CompletableFuture<List<Product>> productFuture = CompletableFuture
.supplyAsync(() -> productService.getRecommendations(userId), executor);
CompletableFuture<List<Coupon>> couponFuture = CompletableFuture
.supplyAsync(() -> couponService.getAvailableCoupons(userId), executor);
CompletableFuture.allOf(userFuture, productFuture, couponFuture).join();
return HomePageVO.builder()
.userInfo(userFuture.join())
.products(productFuture.join())
.coupons(couponFuture.join())
.build();
}
}</code></pre>
<h2>四、异常处理</h2>
<pre><code>CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> { if (Math.random() > 0.5) throw new RuntimeException("异常"); return "成功"; })
.exceptionally(ex -> { log.error("任务异常", ex); return "默认值"; })
.handle((result, ex) -> { if (ex != null) return "处理异常"; return "处理结果: " + result; });</code></pre>
<h2>五、最佳实践</h2>
<ol>
<li>必须自定义线程池</li>
<li>避免 get() 阻塞</li>
<li>异常不能吞掉</li>
</ol>
<h2>总结</h2>
<p>CompletableFuture 是 Java 异步编程的利器。核心记住:supplyAsync 创建任务、thenApply/thenCompose 编排任务、exceptionally 处理异常。</p>
</div>
<div id="MySignature" role="contentinfo">
---
📌 **如果觉得文章对你有帮助,欢迎点赞👍收藏⭐!**
💬 有问题或建议?欢迎在评论区留言讨论~
🔗 更多技术干货请关注作者:弥烟袅绕
📚 本文地址:https://www.cnblogs.com/czlws/p/19794819<br><br>
来源:https://www.cnblogs.com/czlws/p/19794819
頁:
[1]