Java concurrency: Countdown latch vs Cyclic barrier

There’s another difference.

When using a CyclicBarrier, the assumption is that you specify the number of waiting threads that trigger the barrier. If you specify 5, you must have at least 5 threads to call await().

When using a CountDownLatch, you specify the number of calls to countDown() that will result in all waiting threads being released. This means that you can use a CountDownLatch with only a single thread.

“Why would you do that?”, you may say. Imagine that you are using a mysterious API coded by someone else that performs callbacks. You want one of your threads to wait until a certain callback has been called a number of times. You have no idea which threads the callback will be called on. In this case, a CountDownLatch is perfect, whereas I can’t think of any way to implement this using a CyclicBarrier (actually, I can, but it involves timeouts… yuck!).

I just wish that CountDownLatch could be reset!

Leave a Comment