首頁 > Java > java教程 > 主體

本週我學習了:CompletableFuture – Java 的非同步程式設計方法

WBOY
發布: 2024-08-01 06:51:43
原創
850 人瀏覽過

This Week I Learnt: CompletableFuture – Java

本週,我將深入研究 Java 的 CompletableFuture。

身為一名有前端背景的全端開發人員,處理非同步任務是我角色中不可避免的一部分——網路請求、後台運算等。在 Java 中,CompletableFuture 是一個強大的工具,用於處理這些任務,同時保持主執行緒回應。

Completable futures 之於 Java 就像 Promises 之於 JavaScript。

如果您熟悉 JavaScript,透過比較兩種語言可能有助於掌握這些概念。我喜歡將 CompletableFuture 視為 Java 版本的 Promise。它是一個表示非同步操作的最終結果的類,無論該結果是成功還是失敗。它作為 java.util.concurrent 套件的一部分在 Java 8 中引入,是一種編寫非阻塞程式碼的強大方法,具有連結操作和處理錯誤的方法,與 Promises 類似。

這是兩者的快速比較:

// JavaScript Promise
fetchFromServer()
    .then(data => processData(data))
    .then(result => updateUI(result))
    .catch(error => handleError(error));
登入後複製
// Java CompletableFuture
CompletableFuture.supplyAsync(() -> fetchDataFromServer())
    .thenApply(data -> processData(data))
    .thenAccept(result -> updateUI(result))
    .exceptionally(error -> handleError(error));
登入後複製

如上所示,CompletableFuture 提供了類似的可連結語法,允許乾淨且可讀的非同步程式碼。

考慮一個場景,您需要從兩個單獨的端點取得使用者的個人資料資料和訂單歷史記錄。您可能希望避免在等待這些請求完成時凍結 UI。以下是使用 CompletableFuture 實現此功能的方法:

CompletableFuture<User> profileFuture = CompletableFuture.supplyAsync(() -> {
    // Fetch user profile from a service
});

CompletableFuture<List<Order>> ordersFuture = CompletableFuture.supplyAsync(() -> {
    // Fetch user orders from another service
});

CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(profileFuture, ordersFuture);

combinedFuture.thenRun(() -> {
    User user = userFuture.join(); 
    List<Order> orders = ordersFuture.join(); 
    displayUserData(user, orders); 
});
登入後複製

在此範例中,我們同時觸發兩個非同步請求,並使用 allOf 等待兩個請求完成。一旦完成,我們就會檢索結果並相應地更新 UI,所有這些都不會阻塞主執行緒。


連結和完成階段

CompletableFuture 實作了 CompletionStage 接口,為鍊式運算提供了基礎。每個 thenApply、thenAccept 和類似方法都會傳回另一個 CompletionStage,讓您可以建立複雜的非同步管道。

類似於當我們要依次執行一系列非同步任務時如何在 JavaScript 中連結 Promise,我們可以在 Completable Future 中連結任務,以便創建一系列依賴的非同步操作,而不會陷入回調地獄。我們的做法如下:

CompletableFuture.supplyAsync(() -> "Hello")
    .thenApply(result -> result + ", CompletableFuture")
    .thenApply(result -> result + " in Java")
    .thenAccept(System.out::println);
登入後複製

處理例外

當我們在 Promise 物件上使用 .catch() 時,我們在 Completable Future 上使用 .exceptionally() 。此方法處理非同步處理過程中可能出現的異常:

CompletableFuture.supplyAsync(() -> {
    if (true) {
        throw new RuntimeException("Exception in CompletableFuture!");
    }
    return "No exception";
}).exceptionally(ex -> {
    System.out.println("Handled exception: " + ex);
    return "Recovered value";
}).thenAccept(System.out::println);
登入後複製

我希望這篇文章為您提供一個很好的起點來進一步探索 CompletableFuture 類別。

有用連結:

  • 並發深度探究:CompletableFuture 指南
  • Java 非同步程式設計綜合介紹 - Promise、Callbacks 和 Futures

以上是本週我學習了:CompletableFuture – Java 的非同步程式設計方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!