user2033382 user2033382 - 4 months ago 20
Java Question

How is CountDownLatch used in Java Multithreading?

Can someone please help me to understand what Java

CountDownLatch
is and when to use it?

I don't have a very clear idea of how this program works. As I understand all three threads start at once and each Thread will call CountDownLatch after 3000ms. So count down will decrement one by one. After latch becomes zero the program prints "Completed". Maybe the way I understood is incorrect.



import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Processor implements Runnable {
private CountDownLatch latch;

public Processor(CountDownLatch latch) {
this.latch = latch;
}

public void run() {
System.out.println("Started.");

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

latch.countDown();
}
}


// -----------------------------------------------------

public class App {

public static void main(String[] args) {

CountDownLatch latch = new CountDownLatch(3); // coundown from 3 to 0

ExecutorService executor = Executors.newFixedThreadPool(3); // 3 Threads in pool

for(int i=0; i < 3; i++) {
executor.submit(new Processor(latch)); // ref to latch. each time call new Processes latch will count down by 1
}


try {
latch.await(); // wait untill latch counted down to 0
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("Completed.");
}

}

Answer

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

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

As soon as count reaches zero, Thread awaiting starts running. One of the disadvantages/advantages of CountDownLatch is that its not reusable once count reaches to zero you can not use CountDownLatch any more.

edit:

Use CountDownLatch when one thread like main thread, requires to wait for one or more thread to complete, before it can start processing.

Classical example of using CountDownLatch in Java is any server side core Java application which uses services architecture, where multiple services are provided by multiple threads and application can not start processing until all services have started successfully.

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