HTML Java

Java Count Down Latch


Count Down Latch

This class is a part of Concurrency API. Using this class we can create synchronization, when we want a thread wait until the count is 0 other finite number of threads finish processing.


Working of CountDownLatch

  • Instance of this class is created with a given count.
  • When a thread call CountDownLatch await() method, then it waits until count 0.
  • It’s the duty of the other threads to call countdown() method of CountDownLatch class when they are completed their execution then. This method decreases the count value by 1.
  • When all threads call the countdown method then count value become 0 then thread waiting because of await () method starts execution.
  • The value of count can’t be reset, we can’t use the same instance when CountDownLatch work is finished. If we call still await() method will not cause any blocking of the thread.

Example

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(3);
Random random = new Random();

Workers firstWorker = new Workers("firstWorker",latch, random.nextInt(5000));
Workers secondWorker = new Workers("secondWorker",latch, random.nextInt(5000));
Workers thirdWorker = new Workers("thirdWorker",latch, random.nextInt(5000));

new Thread(firstWorker, "WT-11").start();
new Thread(secondWorker, "WT-22").start();
new Thread(thirdWorker, "WT-33").start();

try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Finishing the Main Method");
}

}
Try it »

In java threads are executing in Asynchronous manner means there is no guarantee which thread executes first but we can synchronize the threads and every Main program is a thread and its run on separate path (stack) and execution of all the other threads is from main thread.

If you want to create the thread then you need to provoke start() method

And you can call run method but there is no creation of thread happens and this behaves likes normal method call.