CyclicBarrier And CountDownLatch in JAVA

According to java doc Cyclic Barrier is:

A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other.

Now why this barrier is called cyclic:
The barrier is called cyclic because it can be re-used after the waiting threads are released.

Also A CyclicBarrier supports an optional Runnable command that is run once per barrier point i.e. after the last thread in the party arrives, but before any threads are released.

Now lest make one Demo class demonstrating the use of Cyclic Barrier:

Before the code the problem which we will try to solve is:

We will be having one character matrix
like:

char matrix[][] = { { 'D', 'E', 'M', 'O' }, { 'O', 'F' }, { 'C', 'Y', 'C', 'L', 'I', 'C' },
            { 'B', 'A', 'R', 'R', 'I', 'E', 'R' } };

We need to compute the result of each row i.e. the result of row 0 will be DEMO. We will assign each row to different threads and those threads will compute the result in parallel and threads will put their result in an String array.

After that once all thread compute their result we will display all the computed result. So here in this problem all threads has to wait for other threads to complete their work so that we can show the combined result.

Now below is the program:


package com.pract.cyclicbarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class TestCyclicBarrier {

    private static char matrix[][] = { { 'D', 'E', 'M', 'O' }, { 'O', 'F' }, { 'C', 'Y', 'C', 'L', 'I', 'C' },
            { 'B', 'A', 'R', 'R', 'I', 'E', 'R' } };

    private static String result[] = new String[matrix.length];

    private static class ComputeResult extends Thread {
        CyclicBarrier barrier;
        int row;


        public ComputeResult(CyclicBarrier barrier, int row) {
            this.barrier = barrier;
            this.row = row;
        }


        public void run() {
            String resultString = "";
            for (int i = 0; i < matrix[row].length; i++) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                resultString += matrix[row][i];
            }
            
            // print the computed result
            System.out.println("Computed Result of row : " + row + " and Result is : " + resultString);

            result[row] = resultString;

            // wait for others

            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        
        Runnable printAllResult = new Runnable() {
            
            @Override
            public void run() {
                String str ="";
                for(int i = 0; i < result.length; i++){
                    str += result[i] + " ";
                }
                System.out.println("Rsult is :"+ str);
            }
        };
          
        CyclicBarrier barrier = new CyclicBarrier(matrix.length, printAllResult);
        
        for(int i = 0; i < matrix.length; i++){
            new ComputeResult(barrier, i).start();
        }
        
        System.out.println("Waiting......");
    }

}

Here is the output:

Waiting......
Computed Result of row : 1 and Result is : OF
Computed Result of row : 0 and Result is : DEMO
Computed Result of row : 2 and Result is : CYCLIC
Computed Result of row : 3 and Result is : BARRIER
Rsult is : DEMO OF CYCLIC BARRIER 

Now lets come to CountDownLatch :

According to java doc CountDownLatch is:

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon — the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

Here notice the line:- If you need a version that resets the count, consider using a CyclicBarrier.

Below is the demo program for CountDownLatch:

package com.pract.countdownlatch;

import java.util.concurrent.CountDownLatch;

public class CountDoenLatchDemo {

    private static CountDownLatch countDownLatch;
    private static CountDownLatch doneSignal;
    
    private static class Worker extends Thread{
        String name;
        
        public Worker(String name){
            this.name = name;
        }
        
        public void  run(){
            try {
                countDownLatch.await();
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            // do their work
            
            System.out.println(" Resuming work from thread :" + this.name);
            
            doneSignal.countDown();
        }
    }
    
    
    
    public static void main(String[] args) throws InterruptedException {
        countDownLatch = new CountDownLatch(3);
        
        Worker[] workers = {new Worker("Thread-One"), new Worker("Thread-Two")};
        doneSignal = new CountDownLatch(workers.length);
        
        workers[0].start();
        workers[1].start();
        
        for(int i = 0; i< 10; i++){
            Thread.sleep(500);
            System.out.println("Do Something......");
            countDownLatch.countDown();
        }
        
        //wait for all threads to complete their work
        doneSignal.await();
        System.out.println("All threads Completed.......");
            
    }
}

Here is the output:

Do Something......
Do Something......
Do Something......
Do Something......
Do Something......
Do Something......
Do Something......
Do Something......
Do Something......
Do Something......
 Resuming work from thread :Thread-One
 Resuming work from thread :Thread-Two
All threads Completed.......

Leave a Reply