CyclicBarrier in Java

The java.util.concurrent.CyclicBarrier class is a synchronization aid that allows a set of threads to wait for each other until all reaches to a common barrier point.

In other words, consider multiple threads are executing concurrently to finish a task, where each of the thread is responsible for finishing a sub-task. When all the sub-tasks are completed, results from all threads will be accumulated to get the final output. In this execution period each thread can complete their part in different time. But we can proceed only when all threads are done. Now each thread is executing independently. How to tell a Thread to wait for others once it is done? Use CyclicBarrier.

Using cyclic barrier each thread will wait for others to finish their task. So it is an agreement between these concurrent threads to wait for others in some common point, and once all threads reach that point, they will proceed further. Following diagram is explaining the usage of CyclicBarrier.

Threads wait for each other by calling the await() method on the CyclicBarrier. Once all the threads are waiting at the same CyclicBarrier, means all are finished with their respective sub-tasks , At this point all threads are released and can continue running.

How to use CyclicBarriers:

First a new instance of a CyclicBarriers is created by specifying the number of threads that the barrier should wait upon.The constructor for a CyclicBarrier will take a single integer that denotes the number of threads.

CyclicBarrier cyclicBarrier = new CyclicBarrier(numberOfThreads);

Each and every thread does it work and after completing it’s execution, calls await() methods as shown:

public void run() {
	// thread does the computation


core java 12 Java Concurrent Packages 12


Explore Tutu'rself