Senior
What is the purpose of CountDownLatch? How does it differ from CyclicBarrier?
sobes.tech AI
Answer from AI
CountDownLatch and CyclicBarrier are synchronizers from java.util.concurrent, but they serve different purposes.
CountDownLatch is used to wait until a certain number of operations are completed. It is initialized with a number, and each call to countDown() decreases the counter. When the counter reaches zero, waiting threads continue. CountDownLatch cannot be restarted — it is one-time use.
CyclicBarrier allows a group of threads to wait for each other until all have reached the barrier. After all threads call await(), the barrier is reset and can be used again (cyclic).
Example of using CountDownLatch:
CountDownLatch latch = new CountDownLatch(3);
// In threads:
latch.countDown();
// In main thread:
latch.await(); // wait until all 3 countDown calls
Example of using CyclicBarrier:
CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("All threads reached the barrier"));
// In threads:
barrier.await(); // wait for each other
Summary:
- CountDownLatch — one-time, for waiting for operations to complete.
- CyclicBarrier — cyclic, for synchronizing a group of threads at a certain point.