CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started.
Working of CountDownLatch:
When we create an object of CountDownLatch, we specify the number of threads it should wait for, all such thread 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 waiting task starts running.
Example of CountDownLatch in JAVA:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo
{
public static void main(String args[])
throws InterruptedException
{
CountDownLatch latch = new CountDownLatch( 4 );
Worker first = new Worker( 1000 , latch,
"WORKER-1" );
Worker second = new Worker( 2000 , latch,
"WORKER-2" );
Worker third = new Worker( 3000 , latch,
"WORKER-3" );
Worker fourth = new Worker( 4000 , latch,
"WORKER-4" );
first.start();
second.start();
third.start();
fourth.start();
latch.await();
System.out.println(Thread.currentThread().getName() +
" has finished" );
}
}
class Worker extends Thread
{
private int delay;
private CountDownLatch latch;
public Worker( int delay, CountDownLatch latch,
String name)
{
super (name);
this .delay = delay;
this .latch = latch;
}
@Override
public void run()
{
try
{
Thread.sleep(delay);
latch.countDown();
System.out.println(Thread.currentThread().getName()
+ " finished" );
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
|
Output:
WORKER-1 finished
WORKER-2 finished
WORKER-3 finished
WORKER-4 finished
main has finished
Facts about CountDownLatch:
- Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually number of invited parties (threads) for an event.
- The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero.
- countDown() method decrements the count and await() method blocks until count == 0
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Sep, 2023
Like Article
Save Article