CyclicBarrier in Java

cyclic barrier in java

Hello Readers, In this article, we will learn about a very important topic of Java MultiThreading and Concurrency : CyclicBarrier.

This topic is crucially important with respect to interviews on Java for experienced candidates  So let’s get started :

CyclicBarrier:

CyclicBarrier is a class present in the java.util.concurrent package. It was introduced in java 1.5 release. CyclicBarrier is very useful utility for synchronization of threads. It allows set of thread to all wait for each other to reach a common barrier point. Any thread will not continue its execution beyond the barrier point until all threads reaches the barrier point.

This is called cyclic because it can be reused after all threads gets released post waiting.

Important methods present in CyclicBarrier class :

await() :

public int await() throws InterruptedException, BrokenBarrierException

It waits until all threads call await() method on the barrier. It blocks the threads to process further , until all thread reaches the barrier.

Parameterized await() :

public int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException

Simple Illustrative example of CyclicBarrier:

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

 

class TestCyclicBarrier {

 

// It is necessary to declare the InterruptedException using throws keyword in this method as the await() method thows this exception.

public static void main(String args[]) throws InterruptedException {

 

//We are creating here a thread pool.
ExecutorService es = Executors.newFixedThreadPool(2);

 

//Initializing the CyclicBarrier with number of threads/services.

CyclicBarrier barrier = new CyclicBarrier(3);

Thread.sleep(2000);

 

}
}

class MyThread implements Runnable {

CyclicBarrier barrier;

MyThread(CyclicBarrier c) {
this.barrier = c;

}

public void run() {
while (true) {
barrier.await();
}
}
}

It waits until all threads call await() method on the barrier or the specified time elapses.

Thanks for reading this article. I hope , you like it,

For any suggestions / feedback / question / clarification, Kindly post your comments in the below comment box.

Please subscribe our news letter and connect with social media accounts and don’t miss any articles.

Happy Reading!!!

2 Comments on “CyclicBarrier in Java”

  1. I really like your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you? Plz reply as I’m looking to design my own blog and would like to know where u got this from. cheers

Leave a Reply

Your email address will not be published. Required fields are marked *