首页 > 图灵资讯 > 技术篇>正文

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

2024-08-04 17:23:07

本周我学习了: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 提供类似的可链接语法,允许干净和可读的异步代码。

立即学习“Java免费学习笔记(深入);

考虑到一个场景,您需要从两个单独的端点获取用户的个人数据和订单历史记录。您可能希望在等待这些请求完成时避免冻结 ui。以下是使用 completablefuture 实现此功能的方法:

completablefuture<user> profilefuture = completablefuture.supplyasync(() -&gt; {
    // fetch user profile from a service
});

completablefuture<list>&gt; ordersfuture = completablefuture.supplyasync(() -&gt; {
    // fetch user orders from another service
});

completablefuture<void> combinedfuture = completablefuture.allof(profilefuture, ordersfuture);

combinedfuture.thenrun(() -&gt; {
    user user = userfuture.join(); 
    list<order> orders = ordersfuture.join(); 
    displayuserdata(user, orders); 
});
</order></void></list></user>

在这个例子中,我们同时触发两个异步请求,并使用它们 allof 等待两个请求完成。一旦完成,我们将检索结果并相应更新 ui,所有这些都不会阻塞主线程。

链接和完成阶段

completablefuture 实现了 completionstage 接口为链式操作提供了基础。每一个 thenapply、thenaccept 类似的方法将返回另一种方法 completionstage,允许您创建复杂的异步管。

类似于当我们有一系列的异步任务要依次执行时,我们是如何工作的 javascript 中链接 promise,我们可以在 completable future 为了创建一系列依赖的异步操作而不陷入回调地狱,中链接任务。我们将这样做:

completablefuture.supplyasync(() -&gt; "hello")
    .thenapply(result -&gt; result + ", completablefuture")
    .thenapply(result -&gt; result + " in java")
    .thenaccept(system.out::println);

处理异常

当我们在 promise 对象上使用 .catch() 时,我们在 completable future 上使用 .exceptionally() 。异步处理过程中可能出现的异常:

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

我希望这篇文章能为您提供一个进一步探索的好起点 completablefuture 类。

有用链接:

  • 并发深入探讨:completablefuture 指南
  • java 综合介绍异步编程 - promise、callbacks 和 futures

以上是我本周学习的:CompletableFuture – Java 更多关于图灵教育的其他相关文章,请关注异步编程方法的细节!

上一篇 java框架在物联网低功耗设备集成中的应用
下一篇 返回列表

文章素材均来源于网络,如有侵权,请联系管理员删除。