Java CyclicBarriers and the Latches

What are CyclicBarriers and how they are different from Latches?

KRISHNA KISHORE V
7 min readJun 25, 2022

--

https://testwithnishi.com/2019/11/20/overcoming-barriers-to-effective-communications-in-agile-teams/

Before going onto CyclicBarriers let us quickly touch a little upon Latches.

What is a Latch

A Latch is a synchronizer in Java Concurrency Framework and its main focus is waiting for a group of related events to complete. The class CountDownLatch let us implement this behavior. The most important thing about Latches is that they are Use-Once objects; A latch has something known as a terminal state. Once it reaches its terminal state, there is no coming back.

The CountDownLatch is initialized with a count which is the specific number of events to complete. It has two methods countdown() and await(). The threads calling the await() method to wait for the specified number of threads to call the countdown() method representing that they finished the events. If all the threads complete the event then the latch reaches its terminal state.

The latch, reaching its terminal state results in opening its gate. And it never closes. Any number of threads can pass through the gate after the gate is opened.

Any number of threads? What does it mean and how? This is a little important to understand. Let’s say the latch is initialized with the count as 4. And we have 10 threads waiting for the latch to reach its terminal state. In this case, not all 10 threads need to bring the count down. Only 4 out of 10 threads will need to do so. When that happens the latch reaches theterminal state. As the latch reaches the terminal state, not just the four threads that brought the count down to zero but all the 10 threads will be released. Because all the 10 threads waiting for the gate to be opened. All that the threads need for them to be released is, for the latch to reach its terminal state. Hope you have understood.

Now as we already specified, the latches are Use-Once objects, what if we need the same functionality to be repeated more than twice or thrice. Creating those many latches would be a pathetic way of coding it. That’s where Barriers come into the picture.

Barriers work very similarly to latches — In the sense that they are used to make a group of threads waiting. But they can also be…

--

--

KRISHNA KISHORE V

Tech Lead | Full Stack Developer | Software Consultant | Technical Content Writer | Free Lancer