Java Concurrency Interview

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

What is the difference between CountDownLatch and CyclicBarrier?

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.

synchronizers latch barrier

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