CompletableFuture

經資深工程師Justin友人,提醒我Java8還有這東西可以搞一搞,就來試看看發現驚為天人,真是厲害的東西。

CompletableFuture 是 Java 8 中引入的一個非常有用的工具,用於處理非同步任務和並行計算。它提供了一個功能強大的 API,使得處理非同步操作變得簡單且具有可讀性。以下是一些解析和衍生用法:

  1. 非同步操作CompletableFuture 主要用於處理非同步操作。您可以使用 supplyAsyncrunAsync 等方法來啟動非同步操作,並使用 thenApplythenAcceptthenCombine 等方法來處理操作的結果。這使得您可以在不阻塞主線程的情況下執行耗時的操作。

    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
    future.thenApply(result -> result * 2)
          .thenAccept(finalResult -> System.out.println("Final result: " + finalResult));
  2. 組合操作CompletableFuture 允許您組合多個非同步操作,以便在某些操作完成時執行其他操作。這通常使用 thenComposethenCombinethenComposeAsync 等方法實現。

    CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
    CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
    
    CompletableFuture<Integer> combined = future1.thenCombine(future2, (result1, result2) -> result1 + result2);
  3. 異常處理:您可以使用 exceptionallyhandle 等方法來處理異常情況。這使得您能夠優雅地處理錯誤,而不必使用傳統的 try-catch 塊。

    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
        // 可能引發異常的代碼
    });
    
    future.exceptionally(ex -> {
        System.out.println("An exception occurred: " + ex);
        return 0; // 錯誤時返回默認值
    });
  4. 等待多個 CompletableFuture 完成:如果您需要等待多個 CompletableFuture 完成,可以使用 CompletableFuture.allOfCompletableFuture.anyOf

    CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
    CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);
    
    CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(future1, future2);
    allOfFuture.join(); // 等待所有 CompletableFuture 完成
  5. 串行化和並行化CompletableFuture 允許您以串行或並行的方式執行操作,具體取決於您的需求。您可以使用 thenApply 等方法來串行執行操作,或使用 thenApplyAsync 等方法以並行方式執行操作。

    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
    future.thenApplyAsync(result -> result * 2); // 以並行方式執行操作
  6. 等待和獲取結果:最後,要獲取 CompletableFuture 的結果,可以使用 joinget 方法。請注意,join 是一個無異常版本,如果操作引發異常,它會將其包裝為 CompletionException

    CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 42);
    int result = future.join(); // 等待並獲取結果

除了 CompletableFuture,還有其他類似的工具,如 Guava 的 ListenableFuture 和 RxJava 的 Observable,它們提供了不同風格和功能的非同步處理。選擇使用哪個取決於您的項目需求和代碼風格。

還有參考到網路上的資料進行練習

參考網址:https://mahmoudanouti.wordpress.com/2018/01/26/20-examples-of-using-javas-completablefuture/

接過這20個範例練習過後,基本上可以掌握到不少用法,並且可以自行研究衍生用法。 前陣子研究玩Redisson 分布式鎖機制,藉由此次機會來個異種結合,並且觀看其變化。

console log

一方面可以確認分散式鎖正常運作,一方面透過async方式確認程式運作順暢,Java8真的藏很多東西可以學。

Last updated