What is CountDownLatch in Java
CountDownLatch in Java is a kind of synchronizer which allows one Thread to wait for one or more Threads before starts processing. This is a very crucial requirement and often needed in server-side core Java applications and having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap, and BlockingQueue in java.util.concurrent package.
In this Java concurrency tutorial we will what is CountDownLatch in Java, How CountDownLatch works in Java, an example of CountDownLatch in Java, and finally some worth noting points about this concurrent utility.
You can also implement the same functionality using the wait and notify mechanism in Java but it requires a lot of code and getting it to write in the first attempt is tricky,
You can also implement the same functionality using the wait and notify mechanism in Java but it requires a lot of code and getting it to write in the first attempt is tricky,
With CountDownLatch it can be done in just a few lines. CountDownLatch also allows flexibility on the number of threads for which the main thread should wait, It can wait for one thread or n number of threads, there is not much change on code.
The key point is that you need to figure out where to use CountDownLatch in Java application which is not difficult if you understand What is CountDownLatch in Java, What does CountDownLatch does, and How CountDownLatch works in Java.
The key point is that you need to figure out where to use CountDownLatch in Java application which is not difficult if you understand What is CountDownLatch in Java, What does CountDownLatch does, and How CountDownLatch works in Java.
How CountDownLatch works in Java
Now we know What is CountDownLatch in Java, its time to find out How CountDownLatch works in Java. CountDownLatch works in latch principle, the 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 the main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread.
Any thread, usually the main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread.
All other threads are required to do a count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, Thread awaiting starts running.
One of the disadvantages of CountDownLatch is that it's not reusable once count reaches zero you can not use CountDownLatch anymore, but don't worry Java concurrency API has another concurrent utility called CyclicBarrier for such requirements.
One of the disadvantages of CountDownLatch is that it's not reusable once count reaches zero you can not use CountDownLatch anymore, but don't worry Java concurrency API has another concurrent utility called CyclicBarrier for such requirements.
CountDownLatch Example in Java
In this section, we will see a full-featured real-world example of using CountDownLatch in Java. In the following CountDownLatch example, the Java program requires 3 services namely CacheService, AlertService, and ValidationService to be started and ready before the application can handle any request and this is achieved by using CountDownLatch in Java.
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Java program to demonstrate How to use CountDownLatch in Java. CountDownLatch is
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Java program to demonstrate How to use CountDownLatch in Java. CountDownLatch is
* useful if you want to start main processing thread once its dependency is completed
* as illustrated in this CountDownLatch Example
*
* @author Javin Paul
*/
public class CountDownLatchDemo {
public static void main(String args[]) {
final CountDownLatch latch = new CountDownLatch(3);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread alertService = new Thread(new Service("AlertService", 1000, latch));
Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
cacheService.start(); //separate thread will initialize CacheService
alertService.start(); //another thread for AlertService initialization
validationService.start();
// application should not start processing any thread until all service is up
*
* @author Javin Paul
*/
public class CountDownLatchDemo {
public static void main(String args[]) {
final CountDownLatch latch = new CountDownLatch(3);
Thread cacheService = new Thread(new Service("CacheService", 1000, latch));
Thread alertService = new Thread(new Service("AlertService", 1000, latch));
Thread validationService = new Thread(new Service("ValidationService", 1000, latch));
cacheService.start(); //separate thread will initialize CacheService
alertService.start(); //another thread for AlertService initialization
validationService.start();
// application should not start processing any thread until all service is up
// and ready to do there job.
// Countdown latch is idle choice here, main thread will start with count 3
// Countdown latch is idle choice here, main thread will start with count 3
// and wait until count reaches zero. each thread once up and read will do
// a count down. this will ensure that main thread is not started processing
// until all services is up.
//count is 3 since we have 3 Threads (Services)
try{
latch.await(); //main thread is waiting on CountDownLatch to finish
System.out.println("All services are up, Application is starting now");
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
/**
* Service class which will be executed by Thread using CountDownLatch synchronizer.
*/
class Service implements Runnable{
private final String name;
private final int timeToStart;
private final CountDownLatch latch;
public Service(String name, int timeToStart, CountDownLatch latch){
this.name = name;
this.timeToStart = timeToStart;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(timeToStart);
} catch (InterruptedException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println( name + " is Up");
latch.countDown(); //reduce count of CountDownLatch by 1
}
}
Output:
ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now
//count is 3 since we have 3 Threads (Services)
try{
latch.await(); //main thread is waiting on CountDownLatch to finish
System.out.println("All services are up, Application is starting now");
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
/**
* Service class which will be executed by Thread using CountDownLatch synchronizer.
*/
class Service implements Runnable{
private final String name;
private final int timeToStart;
private final CountDownLatch latch;
public Service(String name, int timeToStart, CountDownLatch latch){
this.name = name;
this.timeToStart = timeToStart;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(timeToStart);
} catch (InterruptedException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println( name + " is Up");
latch.countDown(); //reduce count of CountDownLatch by 1
}
}
Output:
ValidationService is Up
AlertService is Up
CacheService is Up
All services are up, Application is starting now
By looking at the output of this CountDownLatch example in Java, you can see that the Application is not started until all services started by individual Threads are completed.
When should we use CountDownLatch in Java
Use CountDownLatch when one of Thread like main thread, require to wait for one or more thread to complete before its start doing the processing.
A classical example of using CountDownLatch in Java is any server-side core Java application that uses services architecture, where multiple services are provided by multiple threads and the application can not start processing until all services have started successfully as shown in our CountDownLatch example.
If you want to learn more, you can further see these online Java Multithreading courses to learn more about Java Concurrency API and other Multithreading concepts.
CountDownLatch in Java – Things to remember
Few points about Java CountDownLatch which is worth remembering:
1) You can not reuse CountDownLatch once the count is reaches zero, this is the main difference between CountDownLatch and CyclicBarrier, which is frequently asked in core Java interviews and multi-threading interviews.
2) Main Thread waits on Latch by calling CountDownLatch.await() method while other thread calls CountDownLatch.countDown() to inform that they have completed.
That’s all on What is CountDownLatch in Java, What does CountDownLatch do in Java, How CountDownLatch works in Java along with a real-life CountDownLatch example in Java. This is a very useful concurrency utility and if you master when to use CountDownLatch and how to use CountDownLatch you will be able to reduce a good amount of complex concurrency control code written using wait and notify in Java.
Other Java concurrency examples from Javarevisited.
And lastly, What is your favorite Java concurrency utility class? CountDownLatch, CyclicBarrier, Phaser, CompletableFuture, ForkJoinPool, Executor or anything else?
21 comments :
I was looking for a tutorial like this which teaches exactly How to use CountDownLatch in Java. to me concurrency seems more difficult than anything else and I am still learning on how to use Java concurrency API like CyclicBarrier, BlockingQueue etc.Thank you so much for making Java concurrency simple for me, with these How to examples.
To make explanation of CountDownLatch more clear :
- CountDownLatch is a synchronization utility, which allows any Thread to wait for certain number of events, triggered by different thread.
- When each event happens, The Thread which completes that event, calls countDown() method of this class. Which reduces count by one. When count reach zero, which confirms that all event has completed, waiting thread wakes up and do its job.
Can you please explain me that if i comment
// validationService.start(); in the main program and keep the count 3, then the main thread keeps on waiting for the count to become zero.
Is there any way to proceed through this situation???
Hello Shravan, in that case main thread will keep waiting to become count to zero, since it's called latch.await(), which is infinite wait. There is an overloaded version of await(long, TimeUnit) which takes a timeout, which is quite possible if one of thread get stuck and could not call count down. After timeout, main thread will be up.
Why cant we user join() rather than this class CountDownLatch ?
but using this threads are not executed in order , which can be achieved using join right ?
Hi, Javin
I want to know whether the execution of main thread strictly depends of latch value i.e. latch= 0 or as usual it depends on schedular
Hi Sudip,
As per my understanding, in this case the execution of main thread will depend on latch value(till it becomes 0), After value is '0' , now the further processing of main thread will depend on scheduler.
Please correct me anyone , anywhere I am wrong.
Question why not to use Thead.join()
In terms of readability, I would choose the CountdownLatch approach over joining on each thread. This also allows you to change the implementation of Item to maybe submit to an Executor service instead of using Threads directly.
Of course Service class should be made static in above example.
Superb , Simple , sweet explanation ,,hats off Javin
@Prem, thanks, good to hear that you find this tutorial helpful.
Jarvin , why the Validation Service starts first while the Cache Service should start first
Please let me know how we can use latch.await() on any other thread apart from main thread.
@Unknown: Just pass the latch instance to that thread and call latch.await() from run() method in that thread.
Well explained.
Thank you @Ashad, glad that you find my explanation of CountDownLatch in Java useful.
Good work, its easy and refined. Keep up the good work
Thank you @Unknown.
Thanks this is useful
Thank Javin Paul for article about CountDownLatch, it very helpful for me.
Btw, i suggest you should compare with Thread join, WorkManager and Executor. These working same CountDownLatch.
Post a Comment