Synchronizers: latches, barriers, semaphores question 51 of 180 mid
How does CompletableFuture.allOf compare to a CountDownLatch for "wait for N tasks"?
- They are equivalent, pick either
- Correct: The latch blocks a thread and carries no results or failures;
allOfcomposes without blocking and propagates both allOfis only for I/O- A latch is faster and should be preferred
A latch is a counter. It tells you that N things finished and nothing else: no values, no exceptions,
no cancellation. You still need somewhere to put the results, usually a concurrent collection, and
somewhere to put the failures, usually an AtomicReference everyone forgets to check. And someone must
block on await().
allOf gives a future that completes when all inputs do, carries each result in its own future, and
completes exceptionally if any input fails. Nothing blocks unless you ask it to.
A latch still wins in two places: coordinating threads you did not start as futures, such as a starting gate in a test, and simple lifecycle signalling ("the server is up"). Structured concurrency covers the fan-out case with cancellation on top, which is the answer to the follow-up about where this is heading, with the caveat that it is still a preview API as of Java 25.
Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction