Java CyclicBarrier

CyclicBarrier Introduction

CyclicBarrier is a synchronization object that will release when a given number of threads are waiting on it. CyclicBarrier is initialized with a count that indicates the number of threads that must wait on this barrier. CyclicBarrier is useful in applications where threads needs to wait for each other. 

Java CyclicBarrier Class

Java supports CyclicBarrier synchronization object. Some of the key APIs of CyclicBarrier class are listed below.

  • CycliBarrier(int count) – Constructor that creates CyclicBarrier with a specified count. Indicates the number of threads that must invoke await before the barrier is released.
  • int await() – Waits till all threads have invoked wait on this barrier.
  • int await(long timeout, TimeUnit unit) – Waits until all threadshave invoked await on this barrier, or the specified waiting time elapses.

Java CyclicBarrier Example

In this example we have a short task and a long task. We use a CyclicBarrier object to make the short task to wait till the long task has completed. 
package com.sourcetricks.cyclicbarrier;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;public class CyclicBarrierExample {private static class MyTask1 implements Runnable {CyclicBarrier barrier;MyTask1(CyclicBarrier barrier) {this.barrier = barrier;}@Overridepublic void run() {System.out.println("In MyTask1 ...");try {Thread.sleep(2000);barrier.await();} catch (InterruptedException | BrokenBarrierException e) {e.printStackTrace();}System.out.println("Completing MyTask1 ...");}}private static class MyTask2 implements Runnable {CyclicBarrier barrier;MyTask2(CyclicBarrier barrier) {this.barrier = barrier;}@Overridepublic void run() {System.out.println("In MyTask2 ...");try {Thread.sleep(10000);barrier.await();} catch (InterruptedException | BrokenBarrierException e) {e.printStackTrace();}System.out.println("Completing MyTask2 ...");}}public static void main(String[] args) {CyclicBarrier barrier = new CyclicBarrier(2);Thread t1 = new Thread(new MyTask1(barrier));Thread t2 = new Thread(new MyTask2(barrier));t1.start();t2.start();}}

This program produces the following output.

In MyTask1 ...In MyTask2 ...Completing MyTask2 ...Completing MyTask1 ...

Read other concurrency tutorials from Java Tutorials page.