javaconcurrencycountdownlatchcyclicbarrier

Java concurrency: Countdown latch vs Cyclic barrier


I was reading through the java.util.concurrent API, and found that

To me both seems equal, but I am sure there is much more to it.

For example, in CoundownLatch, the countdown value could not be reset, that can happen in the case of CyclicBarrier.

Is there any other difference between the two?
What are the use cases where someone would want to reset the value of countdown?


Solution

  • One major difference is that CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met.

    It also allows you to get the number of clients waiting at the barrier and the number required to trigger the barrier. Once triggered the barrier is reset and can be used again.

    For simple use cases - services starting etc... a CountdownLatch is fine. A CyclicBarrier is useful for more complex co-ordination tasks. An example of such a thing would be parallel computation - where multiple subtasks are involved in the computation - kind of like MapReduce.