You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于CompletableFuture.anyOf方法文档表述的技术咨询

Understanding CompletableFuture.anyOf()'s "Same Result" Meaning

Let’s break down exactly what that phrase refers to in plain terms:

  • The "same result" is the outcome—either a successful return value or a thrown exception—of the first CompletableFuture in your input array that finishes executing. This applies whether the future completes normally or hits an error.
  • It doesn’t matter which position the future occupies in the cfs parameter; the moment any of them finishes, the new CompletableFuture returned by anyOf() immediately adopts that future’s result.

Example to Make It Concrete

Suppose you spin up three asynchronous tasks with different wait times:

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
    try { Thread.sleep(3000); } catch (InterruptedException e) {}
    return "Result from slow Future 1";
});

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
    try { Thread.sleep(1000); } catch (InterruptedException e) {}
    return 42;
});

CompletableFuture<Boolean> future3 = CompletableFuture.supplyAsync(() -> {
    try { Thread.sleep(2000); } catch (InterruptedException e) {}
    return true;
});

CompletableFuture<Object> combinedFuture = CompletableFuture.anyOf(future1, future2, future3);

In this scenario, future2 finishes first after 1 second. So combinedFuture will complete with the value 42—exactly the result of the first completed input future.

Edge Case: Exceptional Completion

If the first completed future throws an exception, the combined future will also complete exceptionally with that same error. For example:

CompletableFuture<String> failingFuture = CompletableFuture.supplyAsync(() -> {
    throw new RuntimeException("Oops, failed right away!");
});

CompletableFuture<String> slowFuture = CompletableFuture.supplyAsync(() -> {
    try { Thread.sleep(5000); } catch (InterruptedException e) {}
    return "Late, successful result";
});

CompletableFuture<Object> combined = CompletableFuture.anyOf(failingFuture, slowFuture);

Here, failingFuture completes immediately with an exception, so combined will hold that RuntimeException as its result—completely ignoring the slow, successful future that finishes later.

内容的提问来源于stack exchange,提问作者Venkatesh Laguduva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:25:47