1、CompletableFuture
是一個(gè)可以:
? 異步執(zhí)行任務(wù);
? 串聯(lián)多個(gè)任務(wù);
? 組合多個(gè)并行任務(wù);
? 提供異常與超時(shí)處理;
的強(qiáng)大異步編程工具。
一句話:它讓你寫(xiě)異步代碼,像寫(xiě)同步邏輯一樣自然。
CompletableFuture 常用經(jīng)典場(chǎng)景(項(xiàng)目實(shí)戰(zhàn))
在真實(shí)項(xiàng)目中,CompletableFuture 能顯著提高并發(fā)性能與代碼可讀性。以下是常見(jiàn)的八大場(chǎng)景??
1?? 并行執(zhí)行多個(gè)獨(dú)立任務(wù)(性能提升)
適用于同時(shí)發(fā)起多個(gè)無(wú)依賴請(qǐng)求的場(chǎng)景,例如訂購(gòu)或用戶畫(huà)像模塊:
CompletableFuture<List<Order>> ordersFuture = CompletableFuture.supplyAsync(() -> getUserOrders(userId));
CompletableFuture<List<Recommendation>> recommendFuture = CompletableFuture.supplyAsync(() -> getRecommendations(userId));
// 等待所有任務(wù)完成并組合結(jié)果
CompletableFuture.allOf(userFuture, ordersFuture, recommendFuture).join();
UserProfile profile = new UserProfile(
userFuture.get(),
ordersFuture.get(),
recommendFuture.get()
);
?? 效果:多個(gè)慢請(qǐng)求并行執(zhí)行,整體性能大幅提升。
?
2?? 異步等待響應(yīng)(信令 / 消息場(chǎng)景)
常見(jiàn)于需要等待外部系統(tǒng)回調(diào)的業(yè)務(wù):
CompletableFuture<Response> future = new CompletableFuture<>();
requestMap.put(requestId, future);
sendRequest(request);
try {
return future.get(5, TimeUnit.SECONDS); // 設(shè)置超時(shí)
} catch (TimeoutException e) {
return handleTimeout();
}
?? 用法亮點(diǎn):CompletableFuture 自身就能當(dāng)“Promise”,
可在回調(diào)到來(lái)時(shí) future.complete(response),輕松喚醒等待線程。
?
3?? 鏈?zhǔn)疆惒教幚恚ǘ嗖襟E處理)
適用于數(shù)據(jù)流式處理:
CompletableFuture.supplyAsync(() -> fetchUserData(userId))
.thenApply(UserService::validateUser)
.thenCompose(UserService::loadUserPreferences)
.thenApply(RecommendationService::generateRecommendations)
.thenAccept(RecommendationService::cacheRecommendations)
.exceptionally(this::handleException);
?? 特點(diǎn):可讀性高、模塊化清晰、天然支持異步。
?
4?? 條件分支處理
根據(jù)異步結(jié)果的不同選擇處理邏輯:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> fetchData())
.thenCompose(data -> {
if (data.isComplete()) {
return CompletableFuture.completedFuture(data.getContent());
} else {
return CompletableFuture.supplyAsync(() -> processIncompleteData(data));
}
});
??應(yīng)用場(chǎng)景:數(shù)據(jù)完整性判斷、動(dòng)態(tài)工作流。
?
5?? 超時(shí)控制
保證系統(tǒng)響應(yīng)性:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> longRunningTask());
try {
String result = future.get(3, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
handleTimeout();
}
? 價(jià)值:防止異步任務(wù)無(wú)限等待,保護(hù)主流程。
?
6?? 錯(cuò)誤處理與恢復(fù)機(jī)制
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> riskyOperation())
.exceptionally(e -> {
logger.error("操作失敗", e);
return "default-value";
});
??? 亮點(diǎn):允許設(shè)置降級(jí)值,不影響整體執(zhí)行流。
?
7?? 多任務(wù)結(jié)果組合
CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> service1.getData());
CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> service2.getData());
CompletableFuture<String> combined = f1.thenCombine(f2, (r1, r2) -> r1 + " - " + r2);
?? 場(chǎng)景:微服務(wù)結(jié)果聚合、并發(fā)接口結(jié)果整合。
?
8?? 優(yōu)先級(jí)結(jié)果處理(取最快結(jié)果)
CompletableFuture<String> remote = CompletableFuture.supplyAsync(() -> remoteService.getData());
CompletableFuture<String> cache = CompletableFuture.supplyAsync(() -> cacheService.getData());
CompletableFuture<Object> result = CompletableFuture.anyOf(remote, cache);
?? 效果:適用于多源查詢、冗余備份方案,提升系統(tǒng)響應(yīng)速度。