Synchronizers: latches, barriers, semaphores question 45 of 180 mid
What is the difference between CountDownLatch and CyclicBarrier?
- The barrier is thread safe and the latch is not
- Correct: A latch is one-shot and counted down by anyone; a barrier waits for N parties and resets for reuse
- A latch waits for threads, a barrier waits for time
- They differ only in the method names
A CountDownLatch counts towards zero and stays there. Any thread may call countDown(), including
threads that never wait, and once it opens it can never close. That makes it the tool for "start
everyone at once" and "wait until all N things have happened".
A CyclicBarrier counts arrivals. Each party calls await(), which blocks until the Nth party
arrives, then all are released together and the barrier resets for the next round. The parties are the
waiters, and the count is fixed at construction.
Two more differences worth volunteering. The barrier can run a barrier action, a Runnable executed by
the last arriving thread before the others are released, which is where you merge results between
rounds. And a barrier is fragile: if one party is interrupted or times out, every other party gets a
BrokenBarrierException, because a barrier that cannot reach N is useless to everyone.
Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction