How is CountDownLatch used in Java Multithreading?
Yes, you understood correctly.
CountDownLatch
works in latch principle, the main thread will wait until the gate is open. One thread waits for n threads, specified while creating the CountDownLatch
.
Any thread, usually the main thread of the application, which calls CountDownLatch.await()
will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling CountDownLatch.countDown()
once they are completed or ready.
As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of CountDownLatch
is that it's not reusable: once count reaches zero you cannot use CountDownLatch
any more.
Edit:
Use CountDownLatch
when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.
A classical example of using CountDownLatch
in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.
P.S. OP's question has a pretty straightforward example so I didn't include one.
CountDownLatch
in Java is a type of synchronizer which allows one Thread
to wait for one or more Thread
s before it starts processing.
CountDownLatch
works on latch principle, thread will wait until gate is open. One thread waits for n
number of threads specified while creating CountDownLatch
.
e.g. final CountDownLatch latch = new CountDownLatch(3);
Here we set the counter to 3.
Any thread, usually main thread of application, which calls CountDownLatch.await()
will wait until count reaches zero or it's interrupted by another Thread
. All other threads are required to do count down by calling CountDownLatch.countDown()
once they are completed or ready to the job. as soon as count reaches zero, the Thread
awaiting starts running.
Here the count is get decremented by CountDownLatch.countDown()
method.
The Thread
which calls the await()
method will wait until the initial count reaches to zero.
To make count zero other threads need to call the countDown()
method.
Once the count become zero the thread which invoked the await()
method will resume (start its execution).
The disadvantage of CountDownLatch
is that it's not reusable: once the count become zero it is no longer usable.