What is Count Down Latch in Java and how it is used?
CountDownLatch was introduced with JDK 1.5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package. This class enables a java thread to wait until other set of threads completes their tasks. e.g. Application’s main thread want to wait, till other service threads which are responsible for starting framework services have completed started all services.
CountDownLatch works by having a counter initialized with number of threads, which is decremented (by countDown() method) each time a thread complete its execution. When count reaches to zero, it means all threads have completed their execution, and thread waiting on latch resume the execution. This counter is checked by await() method. await() method is blocked until count reaches zero.
In this, the count cannot be reset, if we want to reset the count, then we should use Cyclic Barrier
Examples -
Use Case 1:- A Multithreaded download manager. The download manager will start multiple threads to download each part of the file simultaneously.(Provided the server supports multiple threads to download). Here each thread will call a countdown method of an instantiated latch. After all the threads have finished execution, the thread associated with the countdown latch will integrate the parts found in the different pieces together into one file
Use Case 2:- Consider a IT world scenario where manager divided modules between development teams (A and B) and he wants to assign it to QA team for testing only when both the teams completes their task. Here manager thread works as main thread and development team works as worker thread. Manager thread waits for development teams thread to complete their task.
Use Case 3:- Consider a Bank that works from morning 9 AM to 3 PM. Bank will be closed only when it serves all the clients that has entered before 3 PM. Bank will remain open unless all customers leave the premises. In this case, Bank is a CountDownLatch Main Client on which "await()" method is applied and Customers are the ones who performs "countDown()" on the latch.