Video in progress
How do you collect the results of several requests with CompletableFuture.allOf, and what happens if one of them fails?
allOf returns a CompletableFuture<Void>, so you get the results with join() on each future separately. If one fails, allOf also ends with an error, but only after all of them have finished, and the remaining requests are not cancelled.
📖 Answer
List<CompletableFuture<Quote>> calls = providers.stream()
.map(p -> CompletableFuture.supplyAsync(() -> p.quote(req), ioPool)
.orTimeout(800, TimeUnit.MILLISECONDS))
.toList();
List<Quote> quotes = CompletableFuture.allOf(calls.toArray(CompletableFuture[]::new))
.thenApply(v -> calls.stream().map(CompletableFuture::join).toList())
.join();
The join() inside thenApply doesn't block: by the time you get there, every future has already finished.
What to know:
allOfdoesn't finish on the first error. Even if one of 5 providers fails at 100 ms, it waits for the rest. That's why each call needs its own timeout;- one error fails the whole result. Often that's not what you want. You want "take whoever answered":
List<CompletableFuture<Optional<Quote>>> safe = calls.stream()
.map(f -> f.thenApply(Optional::of)
.exceptionally(ex -> { log.warn("provayder javob bermadi", ex); return Optional.empty(); }))
.toList();
Now allOf(safe...) doesn't end with an error, and you filter out the empty Optionals.
anyOf gives you the result or error of whichever finishes first, and its type is Object. If you want the first successful answer, anyOf doesn't fit: a single request that fails fast spoils everything. For that you create an empty CompletableFuture yourself and call complete() on every successful result.
And a reminder: even after allOf finishes, slow requests keep running in the background. cancel() doesn't stop them, because CompletableFuture doesn't interrupt the running thread. So give the timeout to the HTTP client itself as well.
Sign up to mark studied questions and save your progress.