CompletableFuture 是 Java 8 引入的異步編程工具,通過鏈式調用和非阻塞操作簡化多線程任務編排。
創建異步任務
1.帶返回值的任務
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
2. ?無返回值的任務
使用 runAsync(),適用于僅執行操作的場景:
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("Running"));
3. ?自定義線程池
默認使用 ForkJoinPool.commonPool(),可通過參數指定自定義線程池優化資源管理:
這里可以結合spring 定義全局線程池來實現統一管理, 使用時將容器中的executor當做入參即可
ExecutorService executor = Executors.newCachedThreadPool();
CompletableFuture.supplyAsync(() -> "Task", executor);
鏈式調用與任務組合
1. ?結果轉換
thenApply():將前序結果轉換為新值:
future.thenApply(s -> s + " World"); // "Hello" → "Hello World"
2. 結果消費
thenAccept():僅消費結果不返回新值:
future.thenAccept(System.out::println); // 輸出結果
3.? 任務串聯
thenCompose():將前序結果作為新異步任務的輸入:
future.thenCompose(s -> CompletableFuture.supplyAsync(() -> s.length()));
4. 并行合并結果
thenCombine():合并兩個獨立任務的結果:
future1.thenCombine(future2, (res1, res2) -> res1 + res2);
5. ?多任務協同
allOf():等待所有任務完成;
anyOf():等待任一任務完成。
CompletableFuture.allOf(future1, future2).thenRun(() -> System.out.println("All done"));
異常處理
捕獲異常并返回默認值
exceptionally():在異常時提供兜底結果:
future.exceptionally(ex -> "Fallback");
統一處理結果與異常
handle():無論成功或失敗均執行操作:
future.handle((res, ex) -> ex != null ? "Error" : res);
超時控制
使用 orTimeout() 設置任務超時,超時后拋出 TimeoutException:
CompletableFuture.supplyAsync(() -> "Task").orTimeout(500, TimeUnit.MILLISECONDS).exceptionally(ex -> "Timeout: " + ex.getMessage());