首页  >  文章  >  Java  >  本周我学习了:CompletableFuture – Java 的异步编程方法

本周我学习了:CompletableFuture – Java 的异步编程方法

WBOY
WBOY原创
2024-08-01 06:51:43855浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn