Code Pumpkin

CountDownLatch | Java Concurrency Utilities

May 5, 2017
Posted by Pumpkin
Subscribe

CountDownLatch in Java Concurrency is a type of synchronizer which allows one Thread to wait for one or more Threads before it starts processing.

You can implement the same functionality using wait() & Notify() mechanism but it requires lot of code and getting it write in first attempt is tricky,  With CountDownLatch it can  be done in just few lines.

It was introduced in Java 5 along with other concurrent classes like CyclicBarrier, ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue within java.util.Concurrent package.


CountDownLatch Exmaple in Java

Here is an easy example to remember its behavior: "4 employees share a common cab while leaving from office.  Driver can lift the car only after all 4 take their seats in the car."

Lets implement above situation using CountDown Latch. For better understanding of this Java program, please read steps mentioned next to the program.


	
import java.util.concurrent.CountDownLatch;
 
/**
 * CountDown Latch is useful if you want to start main processing thread once its 
 * dependency is completed as illustrated in this Example.
 * 
 * In this example, Car can start only after all 4 employees take their seat in the car.
 * 
 */
public class CarDriver{
 
    public static void main(String args[]) {
 
       final CountDownLatch latch = new CountDownLatch(4);
       Thread emp1 = new Thread(new Employee("EMP 1", 1000, latch));
       Thread emp2 = new Thread(new Employee("EMP 2", 1000, latch));
       Thread emp3 = new Thread(new Employee("EMP 3", 1000, latch));
       Thread emp4 = new Thread(new Employee("EMP 4", 1000, latch));
       
      // separate threads will start moving all four employees 
      // from their office to car parking.
 
       emp1.start(); 
       emp2.start(); 
       emp3.start();
       emp4.start();

       
      // Driver should not start car until all 4 employees take their seats in the car.
       
       try
      {
            // carDriver thread is waiting on CountDownLatch to finish
            latch.await();  
            System.out.println("All employees have taken their seat, Driver started the car");
       }
       catch(InterruptedException ie){
           ie.printStackTrace();
       }
       
    }
   
}
 
/**
 * Employee class which will be executed by Thread using CountDownLatch.
 */
class Employee implements Runnable{
    private final String name;
    private final int timeToReachParking;
    private final CountDownLatch latch;
   
    public Employee(String name, int timeToReachParking, CountDownLatch latch){
        this.name = name;
        this.timeToReachParking = timeToReachParking;
        this.latch = latch;
    }
   
    @Override
    public void run() {
        try {
            Thread.sleep(timeToReachParking);
        } catch (InterruptedException ex) {
        	System.err.println("Error : ");
        	ex.printStackTrace();
        }
        System.out.println( name + " has taken his seat");
        latch.countDown(); //reduce count of CountDownLatch by 1
    }
   
}

Output


EMP 4 has taken his seat
EMP 3 has taken his seat
EMP 1 has taken his seat
EMP 2 has taken his seat
All employees have taken their seat, Driver started the car

CountDownLatch

Steps to use CountDown Latch in your Java Program

1. Start main thread

2. Create CountDownLatch with initial count (say count=N for N threads)

CountDownLatch class defines one constructor inside:


//Constructs a CountDown Latch initialized with the given count.
public CountDownLatch(int count) {...}

This count is essentially the number of threads, for which latch should wait. This value can be set only once, and CountDown Latch provides no other mechanism to reset this count.

3. Create and start N threads

4. Call CountDownLatch.await() from main thread

This main thread must call, await() method immediately after starting other threads. The execution will stop on await() method till the time, other threads complete their execution.

5. Call CountDownLatch.countDown() method on completing execution of each Thread

Other N threads must have reference of latch object, because they will need to notify the CountDown Latch object that they have completed their task. This notification is done by method countDown(). Each invocation of method decreases the initial count set in constructor, by 1.

6. resume main thread

when all N threads have call this method, count reaches to zero, and main thread is allowed to resume its execution past await() method.


CountDown Latch can not be reused

One point to remember is CountDown Latch cannot be reused. Once the countdown reaches zero any further call to await() method won't block any thread. It won't throw any exception either.


Points to note

  • CountDownLatch initialized to N, using its constructor, can be used to make one (or more) thread wait until N threads have completed some action.
  • countDown() method is used to decrement the count, once the count reaches zero the latch is released.
  • await() method is used to block the thread(s) waiting for the latch to release.
  • CountDown Latch cannot be reused. Once the countdown reaches zero any further call to await() method won't block any thread.
  • There is a similar concurrency utility called CyclicBarrier, which can also use to simulate this scenario but difference between CountDown Latch  and CyclicBarrier is that you can reuse the cyclic barrier once the barrier is broken, but you cannot reuse the CountDownLatch one count reaches to zero. For more details on the differences between them, read our post CountDownLatch Vs CyclicBarrier | Java Concurrency Utilities
  • Java 7 also introduced a flexible alternative of CountDownLatch, known as Phaser. It also has number of unarrived party just like barrier and latch but that number is flexible. 


Download Complete Java Program »

Tags: , , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank