CountDownLatch is a kind of synchronizer which is used to make sure that a thread will wait until another set of threads completes their tasks. A very good example of CountDownLatch is the server where the main task can only start when all the required services have started.
A CountDownLatch is initialized with a given count and the count is decremented by calls to the countDown() method. When the count reaches to zero, it means all threads have completed their execution and thread which is waiting on latch resume the execution. await() method blocks the execution of the current thread until the count reaches zero.
This is a one-shot phenomenon i.e. the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
A simple example of CounDownLatch in Java
Example, In which is mocking the Application Servers using countdown latch
Usages of CountDownLatch in java
1. Achieving Maximum Parallelism
Sometimes we want to start a number of threads at the same time to achieve maximum parallelism. For example, we want to test a class for being a singleton. This can be done easily if we create a CountDownLatch with initial count 1, and make wait for all threads to wait for the latch. A single call to countDown() method will resume execution for all waiting threads at the same time.
2. Wait for N threads to complete before start execution
For example, an application start-up class wants to ensure that all N external systems are UP and running before handling the user requests.
3. Deadlock detection
A very handy use case in which you can use N threads to access a shared resource with the different number of threads in each test phase, and try to create a deadlock.