关于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
cfsparameter; the moment any of them finishes, the new CompletableFuture returned byanyOf()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
相关产品推荐
相关产品推荐

