CountDownLatch in Java Concurrency

Category : Java | Sub Category : ExecutorService | By Prasad Bonam Last updated: 2021-04-20 03:31:01 Viewed : 475


CountDownLatch in Java Concurrency

What is CountDownLatch?

In CountDownLatch, it enables one thread (calling thread) to wait until other threads completes their tasks.

e.g. Assume that a situation where the application’s main thread want to wait until other service threads have completed their works. (media player will wait until the file is loaded, initialized and making ready for the playing)

CountDownLatch works by having a counter initialized with number of threads, which is decremented each time a thread complete its execution (by calling countDown() method available in the CountDownLatch class). When count reaches to zero, it means all threads have completed their execution, and the thread waiting on latch (caller thread)  resume its execution.

 

How CountDownLatch works?

CountDownLatch.java class defines one constructor inside:

public CountDownLatch(int count) {...}

This will create a CountDownLatch that will wait until the given number of thread completes their executions.

e.g:-

CountDownLatch latch1 = new CountDownLatch(4);
latch1.await();

The latch1.await()  hold the currently running thread until 4 threads have completed their execution with latch1. each completion is acknowledged to latch1 with countDown() method.

 This count is essentially the number of threads, for which latch should wait. This value can be set only once, and CountDownLatch provides no other mechanism to reset this count. (You cannot reset or change this value later)

The first interaction with CountDownLatch is made by the main thread (caller thread) which is going to wait for other threads.

This main thread (caller thread) must call, CountDownLatch.await() method immediately after starting other threads. Then await() method will hold the execution of the caller thread until all the given threads are executed. The execution of the await() method will be expired once the count of the CountDownLatch is zero and the caller method will be resumed.

(as i have mentioned earlier, each thread should call the countDown() method on the latch upon completion of the thread. each countDown() call will decrement the count value by one)

 

CountdownLatch_example.png

Lets look at the diagram in detailed.

ThreadA (the main thread) has created a CountDownLatch that should wait for  3 number of threads.

ThreadA has created another three threads and started them. As soon as they are started,  ThreadA call the await() method of the CountDownLatch.

The await() method holds the execution of the caller method (that is ThreadA) until the specified number of threads (In this case three threads) are completed (in the CountDownLatch).

Each thread should call the countDown() method of the CountDownLatch upon completion of its execution.  countDown() method will decrement the count value of the CountDownLatch by one.

As soon as the count is zero, CountdownLatch get to know that all the threads has completed their tasks. Therefore the caller thread (ThreadA) that is waiting on the CountDownLatch will be resumed.

 

Now lets look at the code implementation for the above scenario.

class WorkerThread implements Runnable
{
private String name;
private CountDownLatch countDownLatch;
WorkerThread(String name, CountDownLatch countDownLatch)
{
this.name = name;
this.countDownLatch = countDownLatch;
}
@Override
public void run()
{
try {
Thread.sleep(5000);
System.out.println(" thread [" + name + "] completed ");
countDownLatch.countDown();
} catch (InterruptedException ex) {
System.out.println(" sleeping thread get interrupted ");
}
}
}


 

WorkerThread has been implemented in a way to sleep for 5 seconds. After that it will print the name property and call the countDown() method of the CountDownLatch.

 

public class Application
{
public static void main(String[] args) throws Exception
{
System.out.println(" main thread has started ");
CountDownLatch countDownLatch = new CountDownLatch(4);
WorkerThread workerThread1 = new WorkerThread("thread1", countDownLatch);
WorkerThread workerThread2 = new WorkerThread("thread2", countDownLatch);
WorkerThread workerThread3 = new WorkerThread("thread3", countDownLatch);
WorkerThread workerThread4 = new WorkerThread("thread4", countDownLatch);
new Thread(workerThread1).start();
new Thread(workerThread2).start();
new Thread(workerThread3).start();
new Thread(workerThread4).start();
System.out.println(" all the worker threads have been started. next calling await() method ");
countDownLatch.await();
System.out.println(" Resume the main thread after executing all worker threads");
}
}

After executing the above Application, you will get the following output.

 main thread has started 
 all the worker threads have been started. next calling await() method 
 thread [thread2] completed 
 thread [thread4] completed 
 thread [thread3] completed 
 thread [thread1] completed 
 Resume the main thread after executing of all worker threads

 

Search
Related Articles

Leave a Comment: