【问题标题】:Get individual results from CompletableFuture.allof()从 CompletableFuture.allof() 获取单个结果
【发布时间】:2025-12-10 23:10:01
【问题描述】:

我有一个类,它使用 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 调用的结果。

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

【问题讨论】:

  • 为什么不能将两次调用的结果存储在一个成员变量中,并在finalFuture的下一个CompletionStage中访问?

标签: java concurrency completable-future


【解决方案1】:

the JavaDoc of CompletableFuture.allOf()所示:

否则,给定 CompletableFuture 的结果(如果有)不会反映在返回的 CompletableFuture 中,但可以通过单独检查它们获得

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

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

【讨论】: