Difference Between CountDownLatch And CyclicBarrier in Java

10 May, 2022
In spite of the fact that both CountDownLatch and CyclicBarrier are utilized as a synchronization help that permits at least one thread to wait however there are sure contrasts between them. Knowing those contrasts between CountDownLatch and CyclicBarrier in Java will assist you with choosing when one of these utilities will serve you better and obviously it is a decent java inquiry question as well.
CountDownLatch is a thread waiting for multiple threads to finish or calling countDown(). When all threads have called countDown(), the awaiting thread continues to execute.
Example: 
Java
// Java Program to demonstrate Usage of CountDownLatch// Its used when a thread needs to wait for other// threads before starting its work // Importing required classesimport java.util.concurrent.CountDownLatch; // Main classpublic class CountDownLatchDemo {     // Main driver method    public static void main(String args[])        throws InterruptedException    {        // Let us create task that is going to        // wait for four threads before it starts        CountDownLatch latch = new CountDownLatch(4);         // Creating worker threads        Worker first = new Worker(1000, latch, "WORKER-1");        Worker second = new Worker(2000, latch, "WORKER-2");        Worker third = new Worker(3000, latch, "WORKER-3");        Worker fourth = new Worker(4000, latch, "WORKER-4");         // Starting above 4 threads        first.start();        second.start();        third.start();        fourth.start();         // The main task waits for four threads        latch.await();         // Main thread has started        System.out.println(Thread.currentThread().getName()                           + " has finished");    }} // A class to represent threads for which// the main thread waits.class Worker extends Thread {    private int delay;    private CountDownLatch latch;     public Worker(int delay, CountDownLatch latch,                  String name)    {        super(name);        this.delay = delay;        this.latch = latch;    }     @Override public void run()    {        try {            Thread.sleep(delay);            latch.countDown();            System.out.println(                Thread.currentThread().getName()                + " finished");        }        catch (InterruptedException e) {            e.printStackTrace();        }    }}
WORKER-1 finished
WORKER-2 finished
WORKER-3 finished
main has finished
WORKER-4 finished

CyclicBarrier is when different threads hang tight for one another(wait for each other)and when all have finished their execution, the result needs to be combined in the parent thread.
Example
Java
// Java program to demonstrate Execution on Cyclic Barrier // Importing required classesimport java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException; // Class 1// Class implementing Runnable interfaceclass Computation1 implements Runnable {     public static int product = 0;    public void run()    {        product = 2 * 3;        try {            // thread1 awaits for other threads            Tester.newBarrier.await();        }        catch (InterruptedException               | BrokenBarrierException e) {            e.printStackTrace();        }    }} // Class 2// Implementing Runnable interfaceclass Computation2 implements Runnable {     public static int sum = 0;    public void run()    {        // check if newBarrier is broken or not        System.out.println("Is the barrier broken? - "                           + Tester.newBarrier.isBroken());        sum = 10 + 20;        try {            Tester.newBarrier.await(3000,                                    TimeUnit.MILLISECONDS);             // number of parties waiting at the barrier            System.out.println(                "Number of parties waiting at the barrier "                + "at this point = "                + Tester.newBarrier.getNumberWaiting());        }        catch (InterruptedException               | BrokenBarrierException e) {            e.printStackTrace();        }        catch (TimeoutException e) {            e.printStackTrace();        }    }} public class Tester implements Runnable {     // create a static CyclicBarrier instance    public static CyclicBarrier newBarrier        = new CyclicBarrier(3);     public static void main(String[] args)    {        // parent thread        Tester test = new Tester();         Thread t1 = new Thread(test);         // Starting the thread using start() method        t1.start();    }     // Method    public void run()    {        // Print statement        System.out.println(            "Number of parties required to trip the barrier = "            + newBarrier.getParties());        System.out.println(            "Sum of product and sum = "            + (Computation1.product + Computation2.sum));         // Creating object of class 1 objects        // on which the child thread has to run        Computation1 comp1 = new Computation1();        Computation2 comp2 = new Computation2();         // creation of child thread        Thread t1 = new Thread(comp1);        Thread t2 = new Thread(comp2);         // Moving child thread to runnable state        t1.start();        t2.start();         try {            // parent thread awaits            Tester.newBarrier.await();        }         catch (InterruptedException               | BrokenBarrierException e) {             // Display exceptions along with line number            // using printStackTrace() method            e.printStackTrace();        }         // barrier breaks as the number of thread waiting        // for the barrier at this point = 3        System.out.println(            "Sum of product and sum = "            + (Computation1.product + Computation2.sum));         // Resetting the newBarrier        newBarrier.reset();        System.out.println("Barrier reset successful");    }}
Number of parties required to trip the barrier = 3
Sum of product and sum = 0
Is the barrier broken? - false
Number of parties waiting at the barrier at this point = 0
Sum of product and sum = 36
Barrier reset successful
Difference between CountDownLatch and CyclicBarrier 
CountDownLatch
CyclicBarrier
thejavamentor
Java-Multithreading
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Compile-time and Run-time Polymorphism in Java
Similarities and Difference between Java and C++
Difference between Internal and External fragmentation
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java