CountDownLatch in java

CountDownLatch in java
As per java docs, CountDownLatch is synchronisation aid that allows one or more threads to wait until set of operations being performed in other threads completes.
So in other words, CountDownLatch waits for other threads to complete set of operations.
CountDownLatch is initialized with count. Any thread generally main threads calls latch.awaits() method, so it will wait for either count becomes zero or it’s interrupted by another thread and all other thread need to call latch.countDown() once they complete some operation.

So count is reduced by 1 whenever latch.countDown() method get called, so  if count is n that means count can be used as n threads have to complete some action or some action have to be completed n times.

One of disadvantage of CountDownLatch is you can not reuse it once count is zero. For that ,you need to use CyclicBarrier.

For example:

Below diagram will make you clear. It is an example how CountDownLatch can be used.

Let’s say, you are developing an application, so it’s main thread has to wait for other services (threads) such as UI initialization, database initialization and logging services to get completed.  So Countdownlatch will be initialized with 3 and main thread will call await()  method and each services will call latch.countDown() once they are about to complete.
CountDownLatch in java

Program :

Create a class named UIInitialization.java. This thread will execute latch.countDown() once it completes.
Create a class named LoggingInitialization.java. This thread will execute latch.countDown() once it completes.

Create a class named DatabaseInitialization.java. This thread will execute latch.countDown() once it completes.

Create a class CountDownLatchMain.java. This will be main thread which will wait for UIInitialization, DatabaseInitialization and LoggingInitialization.
When you run above program, you will get following output:

Why not use join instead of CountDownLatch:

As you might know you can use join for this situation too but you have to manually handles it. Most of people use [ExecutorService](https://java2blog.com/java-executorservice-example-using-callable-future/ “ExecutorService”) for handling threads now and CountDownLatch works good with it. As CountDownLatch is task oriented , you can submit multiple tasks to thread pool and CountDownLatch will ensure execution of original thread once set of other  dependent threads get completed.

Please go through  top 50 core java interview questions for more interview questions.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *