CyclicBarrier in java - Detailed explanation with full program




In this thread concurrency tutorial we will learn what is java.util.concurrent.CyclicBarrier in java with program and examples. Programs to demonstrate usage of CyclicBarrier in thread concurrency in java.

Contents of page :
  • 1) What is java.util.concurrent.CyclicBarrier in java?
  • 1.1) CyclicBarrier’s  constructor in java >
    • CyclicBarrier(int parties)
    • CyclicBarrier(int parties, Runnable barrierAction)
  • 1.2) CyclicBarrier’s await() method has 2 forms in java :
  • int await()
  • int await(long timeout, TimeUnit unit)
  • 2) Program to demonstrate usage of CyclicBarrier in java >
    • 2.1) Let’s discuss output in detail, to get better understanding of CyclicBarrier usage in program in java >
  • 3) Why barrier is called Cyclic in java?
  • 4) Application of CyclicBarrier in real world >


1) What is java.util.concurrent.CyclicBarrier in java?
There might be situation where we might have to trigger event only when one or more threads completes certain operation.

2 or more threads wait for each other to reach a common barrier point. When all threads have reached common barrier point (i.e. when all threads have called await() method) >
  • All waiting threads are released, and
  • Event can be triggered as well.

1.1) CyclicBarrier’s  constructor in java >
  • CyclicBarrier(int parties)
New CyclicBarrier is created where parties number of thread wait for each other to reach common barrier point, when all threads have reached common barrier point, parties number of waiting threads are released.

  • CyclicBarrier(int parties, Runnable barrierAction)
New CyclicBarrier is created where parties number of thread wait for each other to reach common barrier point, when all threads have reached common barrier point, parties number of waiting threads are released and barrierAction (event) is triggered.


1.2) CyclicBarrier’s await() method has 2 forms in java :
  • int await() throws InterruptedException, BrokenBarrierException
If the current thread is not the last to arrive(i.e. call await() method) then it waits until one of the following things happens -
  • The last thread to call arrive(i,.e. call await() method), or
  • Some other thread interrupts the current thread, or
  • Some other thread interrupts one of the other waiting threads, or
  • Some other thread times out while waiting for barrier, or
  • Some other thread invokes reset() method on this cyclicBarrier.

  • int await(long timeout, TimeUnit unit) throws InterruptedException, BrokenBarrierException, TimeoutException
If the current thread is not the last to arrive(i.e. call await() method) then it waits until one of the following things happens -
  • The last thread to call arrive(i,.e. call await() method), or
  • The specified timeout elapses, or
  • Some other thread interrupts the current thread, or
  • Some other thread interrupts one of the other waiting threads, or
  • Some other thread times out while waiting for barrier, or
  • Some other thread invokes reset() method on this cyclicBarrier.


2) Program to demonstrate usage of CyclicBarrier in java >
package CyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class CyclicBarrierTest {
   public static void main(String[] args) {
          /*
          * Create CountDownLatch with 3 parties, when all 3 parties
          * will reach common barrier point CyclicBarrrierEvent will be
          * triggered i.e. run() method of CyclicBarrrierEvent will be called
          */
          CyclicBarrier cyclicBarrier=new CyclicBarrier(3 ,new CyclicBarrrierEvent());
          System.out.println("CountDownLatch has been created with parties=3,"
                       + " when all 3 parties will reach common barrier point "
                       + "CyclicBarrrierEvent will be triggered");
          MyRunnable myRunnable1=new MyRunnable(cyclicBarrier);
         
          //Create and start 3 threads
          new Thread(myRunnable1,"Thread-1").start();
          new Thread(myRunnable1,"Thread-2").start();
          new Thread(myRunnable1,"Thread-3").start();
         
   }
}




class MyRunnable implements Runnable{
   CyclicBarrier cyclicBarrier;
  
   MyRunnable(CyclicBarrier cyclicBarrier){
          this.cyclicBarrier=cyclicBarrier;
   }
  
   @Override
   public void run() {
         
          System.out.println(Thread.currentThread().getName() +
                       " is waiting for all other threads to reach common barrier point");
          try {
                 Thread.sleep(1000);
                 /*
                 * when all 3 parties will call await() method (i.e. common barrier point)
                 * CyclicBarrrierEvent will be triggered and all waiting threads will be released.
                 */
                 cyclicBarrier.await();
          } catch (InterruptedException e) {
                 e.printStackTrace();
          } catch (BrokenBarrierException e) {
                 e.printStackTrace();
          }         
         
          System.out.println("As all threads have reached common barrier point "
                       + Thread.currentThread().getName() +
                       " has been released");
   }
  
}




class CyclicBarrrierEvent implements Runnable{
   public void run() {
          System.out.println("As all threads have reached common barrier point "
                       + ", CyclicBarrrierEvent has been triggered");
   }
  
}
/*OUTPUT
CountDownLatch has been created with parties=3, when all 3 parties will reach common barrier point CyclicBarrrierEvent will be triggered
Thread-1 is waiting for all other threads to reach common barrier point
Thread-2 is waiting for all other threads to reach common barrier point
Thread-3 is waiting for all other threads to reach common barrier point
As all threads have reached common barrier point , CyclicBarrrierEvent has been triggered
As all threads have reached common barrier point Thread-1 has been released
As all threads have reached common barrier point Thread-3 has been released
As all threads have reached common barrier point Thread-2 has been released
*/

2.1) Let’s discuss output in detail, to get better understanding of CyclicBarrier usage in program in java >

Note : I have mentioned output in green text.


CountDownLatch has been created with parties=3, when all 3 parties will reach common
barrier point CyclicBarrrierEvent will be triggered
CountDownLatch has been created with parties=3, when Thread-1, Thread-2 and Thread-3 will call await() method, CyclicBarrrierEvent will be triggered

Thread-1 is waiting for all other threads to reach common barrier point
Thread-1 has called await(), it is waiting for Thread-2 and Thread-3 to call await() method

Thread-2 is waiting for all other threads to reach common barrier point
Thread-1 and Thread-2 has called await(), and they are waiting for Thread-3 to call await() method

Thread-3 is waiting for all other threads to reach common barrier point
Thread-1, Thread-2, and Thread-3 has called await().


As all threads have reached common barrier point , CyclicBarrrierEvent has been triggered
As Thread-1, Thread-2, and Thread-3 has called await(). So, CyclicBarrrierEvent is triggered  i.e. run() method of CyclicBarrrierEvent is called

As all threads have reached common barrier point Thread-1 has been released
As all threads have reached common barrier point Thread-3 has been released
As all threads have reached common barrier point Thread-2 has been released
As Thread-1, Thread-2, and Thread-3 has called await(), all waiting threads are released and completes there execution.

3) Why barrier is called Cyclic in java?
The barrier is called cyclic because CyclicBarrier can be reused after -
  • All the waiting threads are released and
  • event has been triggered.

When we execute 3 more threads in above program CyclicBarrrierEvent will be triggered again.

             
//Create and start 3 threads
new Thread(myRunnable1,"Thread-1").start();
new Thread(myRunnable1,"Thread-2").start();
new Thread(myRunnable1,"Thread-3").start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Create and start 3 more threads
new Thread(myRunnable1,"Thread-4").start();
new Thread(myRunnable1,"Thread-5").start();
new Thread(myRunnable1,"Thread-6").start();

Output will be -

/*OUTPUT
CountDownLatch has been created with parties=3, when all 3 parties will reach common barrier point CyclicBarrrierEvent will be triggered
Thread-1 is waiting for all other threads to reach common barrier point
Thread-2 is waiting for all other threads to reach common barrier point
Thread-3 is waiting for all other threads to reach common barrier point
As all threads have reached common barrier point , CyclicBarrrierEvent has been triggered
As all threads have reached common barrier point Thread-3 has been released
As all threads have reached common barrier point Thread-2 has been released
As all threads have reached common barrier point Thread-1 has been released


Thread-4 is waiting for all other threads to reach common barrier point
Thread-5 is waiting for all other threads to reach common barrier point
Thread-6 is waiting for all other threads to reach common barrier point
As all threads have reached common barrier point , CyclicBarrrierEvent has been triggered
As all threads have reached common barrier point Thread-6 has been released
As all threads have reached common barrier point Thread-4 has been released
As all threads have reached common barrier point Thread-5 has been released
*/



4) Application of CyclicBarrier in real world >
Let’s say 10 friends (friends are threads) have planned for picnic on place A (Here place A is common barrier point). And they all decided to play certain game (game is event) only on everyones arrival at place A. So, all 10 friends must wait for each other to reach place A before launching event.

Now, when all threads have reached common barrier point (i.e. all friends have reached place A) >
  • All waiting threads are released  (All friends can play game), and
  • Event can be triggered (they will start playing game).


SUMMARY>
In this thread concurrency tutorial we learned what is java.util.concurrent.CyclicBarrier in java with program and examples. We also wrote programs to demonstrate usage of CyclicBarrier in thread concurrency in java.




Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

java.util.concurrent.CountDownLatch >

java.util.concurrent.CountDownLatch in java

Implementation of custom/own CountDownLatch in java


Thread concurrency Interviews >

eEdit
Must read for you :