登录
首页 >  文章 >  java教程

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

来源:dev.to

时间:2024-08-01 08:09:43 477浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《本周我学习了:CompletableFuture – Java 的异步编程方法》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

本周我学习了: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 的异步编程方法》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>