Java Concurrency Interview

Synchronizers: latches, barriers, semaphores question 51 of 180 mid

How does CompletableFuture.allOf compare to a CountDownLatch for "wait for N tasks"?

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.

synchronizers completablefuture design

Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction