Synchronizers: latches, barriers, semaphores question 54 of 180 mid
Which synchroniser would you choose, and how do you decide?
- Always a
CountDownLatch, it is the simplest - Correct: By what the waiting means: a one-shot event, a repeated meeting of N parties, a concurrency cap, or a handoff of data
- By how many threads there are
- By whether the code is CPU-bound
The question behind the question is whether you reach for a primitive or for a queue, so answer with the decision rather than the list:
- One-shot event, "wait until X has happened":
CountDownLatch, or aCompletableFutureif a value or a failure needs to travel with it. - Repeated meeting of a fixed set of workers:
CyclicBarrier, with a barrier action for the between-rounds work. - The same, with a changing set of workers:
Phaser. - At most N at a time:
Semaphore, sized after the resource, not after the threads. - Handing data over: a
BlockingQueue, or anExchangerfor a symmetric two-party swap. - Fan-out and fan-in with results, failures and cancellation:
CompletableFutureorStructuredTaskScope, not a latch plus a concurrent collection.
And the meta-answer that earns the point: if you can express it as a queue between threads, do that instead. A queue carries the data, provides the happens-before edge and gives you backpressure, which none of these primitives do on their own.
Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction