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:
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
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java.util.concurrent.RecursiveTask class in Java with Examples
- Java.lang.Short toString() method in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java.util.function.IntPredicate interface in Java with Examples
- Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
- Java.util.function.DoublePredicate interface in Java with Examples
- Java.util.function.BiPredicate interface in Java with Examples
- Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
- Java.util.concurrent.RecursiveAction class in Java with Examples
Improved By : chantiya chowhai