gpt4 book ai didi

java - 从 CompletableFuture.allof() 获取单独的结果

转载 作者:行者123 更新时间:2023-11-30 06:13:48 28 4
gpt4 key购买 nike

我有一个类,它使用 CompletableFutures 向两个依赖服务发出并发请求。

我的代码如下所示:

@Builder
@Slf4j
public class TestClass {

@NonNull private final ExecutorService threadPool = Executors.newFixedThreadPool(2);
@NonNull private final dependency1Client;
@NonNull private final dependency2Client;

public void myMethod() {

RequestObject1 firstDependencyRequest = RequestObject1.builder()
.attribute1("someValue")
.attribute2("secondValue");

CompletableFuture<ResultStructure1> future1 = CompletableFuture.supplyAsync(() -> dependency1Client.call(firstDependencyRequest), threadPool);
RequestObject2 secondDependencyRequest = RequestObject2.builder()
.attribute1("someValue")
.attribute2("secondValue");

CompletableFuture<ResultStructure2> future2 = CompletableFuture.supplyAsync(() -> dependency2Client.call(secondDependencyRequest), threadPool);

try {
CompletableFuture finalFuture = CompletableFuture.allOf(future1, future2);

} catch (ExecutionException|InterruptedException e) {
log.error("Exception calling dependency", e);
throw new RuntimeException(e);
}
}
}

我需要对依赖服务的两次调用的结果。如何在不执行阻塞调用的情况下获取它们?我最初以为我会执行 future1 .get(),但这是一个阻塞调用,我必须等到获得第一个 API 调用的结果。

有没有办法获取这两个调用的结果?

最佳答案

the JavaDoc of CompletableFuture.allOf()表示:

Otherwise, the results, if any, of the given CompletableFutures are not reflected in the returned CompletableFuture, but may be obtained by inspecting them individually.

这实际上意味着您必须对它们调用 join()get() 。如果您在 allOf() 之后的链中执行此操作,它不会阻塞,因为它已经保证所有这些都已完成。

请注意,在您的特定情况下,如果您只有 2 个 future ,那么使用 thenCombine() 可能会更简单。这使您可以更轻松地访问 2 个结果。

关于java - 从 CompletableFuture.allof() 获取单独的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664487/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com