Home » Core Java » CountdownLatch in java

CountdownLatch in java

CountDownLatch ::

  1. CountDownLatch is a class present  in java.util.concurrent package.
  2. It is an addition to concurrency which helps one or more threads to wait until a set of operations being performed in other threads completes.
  3. When you declare CountDownLatch  ,it needs to be initialized with a given count.
  4. CountDownLatch  has await() method which is called on object of CountDownLatch  class.
  5. CountDownLatch  has countDown() method which decreases the count value of CountDownLatch  after every invocation.
  6. Once count of CountDownLatch   reaches to zero ,it can not b reused again.
  7. All  the threads invoking await() method  wait at the gate until it is opened by a thread invoking countDown().


Explanation of below Program ::

Here first we define CountDownLatch  with value 3.There are  three classes WatcherService, ValidationService  and HandlerService which implements Runnable.All these threads sleep for 1 second and reaches the gate  and calls countDown() method to reduce the count .Once count reaches to zero ,the gate opens.Main thread waits till the count reaches to zero and gate opens.

Program ::

Output ::

For your reference ,pleas see API Code

Leave a comment

Your email address will not be published. Required fields are marked *

two × 1 =