首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >联合CompletableFuture

联合CompletableFuture
EN

Stack Overflow用户
提问于 2022-07-28 09:29:28
回答 1查看 41关注 0票数 0

我有这样的代码:

代码语言:javascript
复制
CompletableFuture<ApplicationUserDto> byUserName = applicationUserService
                .findByUserName(getCurrentApplicationUserName());

CompletableFuture<List<FocusDto>> focuses = focusService.findMine(byUserName.join().getFacilities());

CompletableFuture.allOf(byUserName, focuses).join();

Iterable<IdmDataFacade> facilities = idmService.lookupFacilities(new HashSet<>(byUserName.join().getFacilities())).toIterable();

所以在focusService.findMine

我依靠的是

applicationUserService.findByUserName(getCurrentApplicationUserName())

但是在我的前端测试中,所有数据都以正确的方式和方式显示。

我在CompletableFuture上读过关于CompletableFuture方法的文章,所以我测试了以下代码:

代码语言:javascript
复制
CompletableFuture<ApplicationUserDto> byUserName = applicationUserService
                .findByUserName(getCurrentApplicationUserName());

CompletableFuture<List<FocusDto>> focuses = byUserName
                .thenComposeAsync((result) -> focusService.findMine(result.getFacilities()));

CompletableFuture.allOf(byUserName, focuses).join();

Iterable<IdmDataFacade> facilities = idmService.lookupFacilities(new HashSet<>(byUserName.join().getFacilities())).toIterable();

这两个代码段导致完全相同的结果。在日志中,我可以看到正在使用的线程。甚至这些都是平等的。

所以我的问题是:

  1. 非常聪明,知道必须等待byUserName完成才能在CompletableFuture中填充参数。

  1. 哪一段代码更适合使用?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-28 09:51:01

  1. 非常聪明,知道必须等待byUserName完成才能在CompletableFuture中填充参数。

这就是.join的目的:等待结果准备好并返回它。如果您编写这样的代码:

代码语言:javascript
复制
CompletableFuture<ApplicationUserDto> byUserName = applicationUserService
                .findByUserName(getCurrentApplicationUserName());

CompletableFuture<List<FocusDto>> focuses = focusService.findMine(byUserName.join().getFacilities());

您正在告诉应用程序阻止执行,并在调用byUserName之前等待findMine完成,这样您就有了.findMine的参数。

这也意味着以后不需要调用.allOf,因为您已经知道byUserName已经完成了。

你可以重写这样的一切:

代码语言:javascript
复制
Iterable<IdmDataFacade> facilities = applicationUserService
                .findByUserName(getCurrentApplicationUserName())
                .thenCompose(byUserNameResult -> focusService
                    .findMine(byUserNameResult.getFacilities())
                    .thenApply(findMineResult -> idmService
                        .lookupFacilities(new HashSet<>(byUserNameResult.getFacilities())).toIterable()
                    )
                )
                .join();

  1. 哪一段代码更适合使用?

谁知道呢?这取决于你在努力实现什么。通常,如果您正在使用.join,那么在每个CompletionStage之后使用它们都是没有意义的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73150449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档