Cyclic barrier in Java

In this tutorial, We’ll learn about Cyclic Barrier in Java.

Cyclic Barrier is basically a synchronizer in JDK5 on java.util.concurrent package. It allows various threads to wait for the execution of each other (i.e, barrier) and then execute themselves.

This concept works parallel to threads. Prior knowledge of Multithreading in Java will be helpful

Difference between Cyclic Barrier and CountDownLatch in Java:

Though this concept is very similar to CountDown Latch, but one cannot use the CountDownLatch if the count arrives at zero. Whereas, one can use the CyclicBarrier again via the reset() method, which restores the Barrier’s initial state.

So CountDownLatch comes in handy when the event requires to be executed just once. This concept can be used when the requirement is for recurring events.

Implementation

In this example, We initialize Cyclic Barrier with 3 parties. This implies – to get through the barrier, 3 threads need to call await() method. Although, these threads call the await method, yet they wouldn’t execute themselves until all of them get through the barrier.

Upon reaching the barrier, each of these threads continues individual execution.

The code begins with importing appropriate Java libraries under the Util package. To learn more about each of these packages and methods, visit the Java libraries official webpage

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Cyclic_Barrier_Execution {

    //Runnable Run_tasK for individual thread
    private static class Run_tasK implements Runnable {

        private CyclicBarrier barie;

        public Run_tasK(CyclicBarrier barie) {
            this.barie = barie;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is now here, waiting on barrier");
                barie.await();
                System.out.println(Thread.currentThread().getName() + " finally got through the barrier");
            } catch (InterruptedException excep) {
                Logger.getLogger(Cyclic_Barrier_Execution.class.getName()).log(Level.SEVERE, null, excep);
            } catch (BrokenBarrierException excep) {
                Logger.getLogger(Cyclic_Barrier_Execution.class.getName()).log(Level.SEVERE, null, excep);
            }
        }
    }

    public static void main(String args[]) {

        //creating Cyclic_Barrier with 3 parties or 3 Threads which have to call await()
        final CyclicBarrier CyBa = new CyclicBarrier(3, new Runnable(){
            @Override
            public void run(){
                //Run_tasK will run as soon as all threads arrive at the barrier
                System.out.println("Now that all of the threads arrived at the barrier, they'll execute themselves!");
            }
        });

        //starting each of thread
        Thread A = new Thread(new Run_tasK(CyBa), "Here's thread 1");
        Thread B = new Thread(new Run_tasK(CyBa), "Okay thread 2");
        Thread C = new Thread(new Run_tasK(CyBa), "Finally thread 3");

        A.start();
        B.start();
        C.start();
     
    }
}

As shown above,

The class Cyclic_Barrier_Execution has an interface Run_task, which runs for each thread.

The object ‘barie’ invokes the await() function which causes the threads to wait until each thread reaches the barrier.

In the void run() function, the catch block plays the role of catching the exception ‘excep’.

In the main section, Run_task will run as soon as all threads arrive at the barrier.

The above threads A, B, C execute themselves upon crossing the barrier.

Output of Cyclic Barrier:

Execution of this code will fetch the following output:

Here's thread 1 is now here, waiting on barrier
Okay thread 2 is now here, waiting on barrier
Finally thread 3 is now here, waiting on barrier
Now that all of the threads arrived at the barrier, they'll execute themselves!
Okay thread 2 finally got through the barrier
Finally thread 3 finally got through the barrier
Here's thread 1 finally got through the barrier

Further reference regarding Java concepts and methods.

Also read: Heap Pollution in Java

Leave a Reply

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