A CountDownLatch is a synchronisation mechanism which allows threads to wait until some events occur. By using CountDownLatch you can wait for events to happen in other threads
and can proceed only if they have completed.
Working
From docs
A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method,
after which all waiting threads are released and any subsequent invocations of await return immediately.
Note: This is a one-shot phenomenon – the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.
There are 3 important methods in CountDownLatch class.
await()
await(long timeout, TimeUnit unit)
countDown()
await()
await() causes current thread to wait until event count in latch reaches to zero (by calling countDown() method on Latch) or thread is interrupted. If Latch has
already zero count, this method returns immediately.
If a thread has interrupted flag set upon entering this method, it will throw InterruptedException and will clear the flag.
await(long timeout, TimeUnit unit)
This method is same as await with one difference. It will stop waiting if given timeout is elapsed.It returns false if waiting timeout elapses and true, if
event count in latch become zero.
If the time is less than or equal to zero, the method will not wait at all.
countDown()
It decrements the latch count if count is greater than zero. If count reaches to zero, it awakes all awaiting threads.
Example
To understand everything I have written, let’s create a scenario in which we can use CountDownLatch. Say, we have 3 threads, first two threads insert value in a shared list
and third thread waits until each of them completes inserts value in the queue.
Once both thread have inserted values, we will calculate sum of those values in third thread.
Now, create a general NumberThread class which inserts values in the list and invokes countDown on latch.
Create ThreadOne class which extends from NumberThread
Create ThreadTwo class which extends from NumberThread
Create ThreadThree class which extends from NumberThread. This class alos overrides the run method and waits for ThreadOne & ThreadTwo to insert value in list by invoking await
on latch.