CompletableFuture and async composition question 97 of 180 mid
What does allOf return, and how do you collect the results?
- A
CompletableFuture<List<T>> - Correct: A
CompletableFuture<Void>that completes when all inputs do; you collect by joining each input afterwards - The first result
- A stream of results
allOf cannot know the types are the same, so it gives you CompletableFuture<Void> as a
completion signal only. The idiom:
List<CompletableFuture<Price>> calls = ids.stream().map(this::fetchAsync).toList();
CompletableFuture<List<Price>> all = CompletableFuture
.allOf(calls.toArray(CompletableFuture[]::new))
.thenApply(ignored -> calls.stream().map(CompletableFuture::join).toList());
The join inside thenApply never blocks, because every future is already complete by then.
Two things to mention: allOf completes exceptionally if any input fails, but it does not cancel the
others, so add a timeout with orTimeout or completeOnTimeout per call. And anyOf returns
CompletableFuture<Object>, which is awkward enough that people usually write their own.
Quiz yourself on CompletableFuture and async composition Suggest a correction