Difference between CountDownLatch and CyclicBarrier in Java

In this article we will see the difference between CountDownLatch and CyclicBarrier in java. This question is related to the concurrency. I have already shared the popular concurrency question, what is  ConcurrentHashMap and how it works internally. Apart from differences, we will discuss similarities and example of CountDownLatch and CyclicBarrier.

Difference between CountDownLatch and CyclicBarrier in Java

1.  Definition : According to Oracle docs,

CountDownLatch  is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

CyclicBarrier is a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

2. Reusable : A CountDownLatch is initialized with given count. count reaches zero by calling of countDown() method. The count can not be reset.

CyclicBarrier is used to reset count. The barrier is called cyclic because it can be reused after the waiting threads are released (or count  become zero). 

Similarities between CountDownLatch and CyclicBarrier

1. Package : Both belongs to the java.util.concurrent package.

2. Waiting : Both CountDownLatch and CyclicBarrier are used to perform a scenario where one Thread waits for one or more Threads to complete there job before starts processing.

3. Added in jdk : Both CountDownLatch and CyclicBarrier added to the jdk 1.5 version.

Points to remember about CyclicBarrier and CountDownLatch

1. The CyclicBarrier uses an all-or-none brokerage model for failed synchronization attempts. If a thread leaves a barrier point prematurely because of interruption, failure or timeout, all other threads waiting at that barrier point will also leave abnormally via BrokenBarrierException .

2. A CyclicBarrier supports an optional Runnable command that is run once per barrier point, after the last thread in the party arrives, but before any threads are released. This barrier action is useful for updating shared-state before any of the parties continue.

3. A useful property of  CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

Please mention in the comments if you want to add any points about CyclicBarrier and CountDownLatch.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry