Home > DeveloperSection > Blogs > What is a CountDownLatch?

What is a CountDownLatch?


Java Java  Threading 
Ratings:
0 Comment(s)
 575  View(s)
Rate this:

What is a CountDownLatch


This is a more advanced type of synchronization 
that can be done with concurrent package.
Consider the example where a organization needs to recruite 3 java
developers . for this HRManager has asked 3 tech leads to take 
interview.
                 The HR manger wants to distribute
 the offer letter. only after all the 3 java developers
have been recruited. In Threading terminology the HR Manger should 
 wait till 3 java developers have been recruited.
import java.util.concurrent.CountDownLatch;

public class HRManager
  {
       public static void main(String args[])
           {
                CountDownLatch countDownLatch=new CountDownLatch(3);
                TechLead techLead1=new TechLead(countDownLatch,"first");
                TechLead techLead2=new TechLead(countDownLatch,"second");
                 TechLead techLead3=new TechLead(countDownLatch,"third");
                   techLead1.start();
                   techLead2.start();
                    techLead3.start();
              try
                 {
                     System.out.println("HR Manger waiting for recruitment to complete----");
                     countDownLatch.await();
                    
                System.out.println("Distribute Offer Letter");
              }catch(InterruptedException e)
                    {
                        e.printStackTrace(); 
                    }
              }
}
class TechLead extends Thread
   {
       CountDownLatch countDownLatch;
            public TechLead(CountDownLatch countDownLatch,String name)
               {
                   super(name);
                    this.countDownLatch=countDownLatch;
                    
               }
 
          public void run()
              {
                  try{
                         Thread.sleep(2000);
                       }catch(InterruptedException e)
                           {
                              e.printStackTrace();
                           }
                System.out.println(Thread.currentThread().getName()+": recruited");
            countDownLatch.countDown();
         }
}

Don't want to miss updates? Please click the below button!

Follow MindStick