CountDownLatch

In this article we will explore following things.


  1. What is CountDownLatch?
  2. Its prominent methods.
  3. General interview questions

CountDownLatch Class was added in java.util.concurrent package of java 1.5. 


Object of this class is initialized with a number(say N) and await() method make the current thread to wait till the CountDownLatch's counter becomes 0, counter is decremented by 1 by each call of countDown() method.

 Following is an example showing CountDownLatch class in action. Example is quite self explanatory.

package com.meritmix.blog.java;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
 * @author Ravi Yadav
 *
 * This is copyright content of MeritMix.com
 * blog address is blog.meritmix.com 
 */
public class CountDownLatchExample {
     private static final int COUNT = 10; 
     public static void main(String args[])
     {
         // CountDownLatch(int count)
         // Constructs a CountDownLatch initialized with the given count.
         CountDownLatch stopSignal = new CountDownLatch(COUNT);
         for (int i = 0; i < COUNT; i++)
         {
             new Thread(new Worker(stopSignal, Integer.toString(i))).start();
         }
         System.out.println("Ask the main thread to wait other worker thread to complete.");
         try
         {
             stopSignal.await();//Blocking call, makes main thread
                  //to wait until count becomes zero.
             //stopSignal.await(5, TimeUnit.SECONDS); // This is the second
             //option, this method will cause the current thread to wait for
             //the specified time and after that it proceed, letting other threads
             // to die their natural death.
         } catch (InterruptedException ex)
         {
             ex.printStackTrace();
         }
         System.out.println("Done");
     }
  
     private static class Worker implements Runnable
     {  
         CountDownLatch stopLatch;
         String name;
         Worker( CountDownLatch stopLatch, String name)
         {
             this.stopLatch = stopLatch;
             this.name = name;
         }
  
         public void run()
         {
             try
             {
                 Thread.sleep(5000); // Wait for 5 seconds to make the 
                      //functionality visible.                    
             } catch (InterruptedException ex)
             {
                 ex.printStackTrace();
             }
             System.out.println("Running: " + name);
             stopLatch.countDown(); // Reduces the count by 1.
         }
     }     
 }
Prominent Methods:

 1. countDown():

 Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

If the current count is greater than zero then it is decremented. If the new count is zero then all waiting threads are re-enabled for thread scheduling purposes.

If the current count equals zero then nothing happens.

2. await():

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted.

If the current count is zero then this method returns immediately.

If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen:

a) The count reaches zero due to invocations of the countDown method; or b)Some other thread interrupts the current thread.

3.await(timeout, TimeUnit):

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted, or the specified waiting time elapses.

If the current count is zero then this method returns immediately with the value true.

If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happen:

If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all.

No comments:

Post a Comment