How is CountDownLatch used in Java Multithreading? How is CountDownLatch used in Java Multithreading? java java

How is CountDownLatch used in Java Multithreading?


Yes, you understood correctly. CountDownLatch works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch.

Any thread, usually the main thread of the application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling CountDownLatch.countDown() once they are completed or ready.

As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch is that it's not reusable: once count reaches zero you cannot use CountDownLatch any more.

Edit:

Use CountDownLatch when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.

A classical example of using CountDownLatch in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.

P.S.OP's question has a pretty straightforward example so I didn't include one.


CountDownLatch in Java is a type of synchronizer which allows one Thread to wait for one or more Threads before it starts processing.

CountDownLatch works on latch principle, thread will wait until gate is open. One thread waits for n number of threads specified while creating CountDownLatch.

e.g. final CountDownLatch latch = new CountDownLatch(3);

Here we set the counter to 3.

Any thread, usually main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or it's interrupted by another Thread. All other threads are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, the Thread awaiting starts running.

Here the count is get decremented by CountDownLatch.countDown() method.

The Thread which calls the await() method will wait until the initial count reaches to zero.

To make count zero other threads need to call the countDown() method.Once the count become zero the thread which invoked the await() method will resume (start its execution).

The disadvantage of CountDownLatch is that it's not reusable: once the count become zero it is no longer usable.


NikolaB explained it very well, However example would be helpful to understand, So here is one simple example...

 import java.util.concurrent.*;  public class CountDownLatchExample {  public static class ProcessThread implements Runnable {    CountDownLatch latch;    long workDuration;    String name;    public ProcessThread(String name, CountDownLatch latch, long duration){        this.name= name;        this.latch = latch;        this.workDuration = duration;    }    public void run() {        try {            System.out.println(name +" Processing Something for "+ workDuration/1000 + " Seconds");            Thread.sleep(workDuration);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(name+ "completed its works");        //when task finished.. count down the latch count...        // basically this is same as calling lock object notify(), and object here is latch        latch.countDown();    }}public static void main(String[] args) {    // Parent thread creating a latch object    CountDownLatch latch = new CountDownLatch(3);    new Thread(new ProcessThread("Worker1",latch, 2000)).start(); // time in millis.. 2 secs    new Thread(new ProcessThread("Worker2",latch, 6000)).start();//6 secs    new Thread(new ProcessThread("Worker3",latch, 4000)).start();//4 secs    System.out.println("waiting for Children processes to complete....");    try {        //current thread will get notified if all chidren's are done         // and thread will resume from wait() mode.        latch.await();    } catch (InterruptedException e) {        e.printStackTrace();    }    System.out.println("All Process Completed....");    System.out.println("Parent Thread Resuming work....");     }  }