Java CountDownLatch Example

CountDownLatch

This is a more advanced type of synchronization that can be done with concurrenct package.
Consider the example where a Organziation needs to recruite 3 Java Developers. For this HR Manager has asked 3 Tech Leads to take interview.
The HR Manager 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.
Lets simulate this with CountDownLatch class.
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 Manager waiting for recruitment to complete...");
   
   countDownLatch.await();
   
   System.out.println("Distribute Offer Letter");
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}


Now lets create Tech Lead's who will take the interviews.

import java.util.concurrent.CountDownLatch;


public class TechLead extends Thread{

 CountDownLatch countDownLatch;
 public TechLead(CountDownLatch countDownLatch,String name){
  super(name);
  this.countDownLatch=countDownLatch;
  
 }
 
 @Override
 public void run() {
  try {
   
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  // TODO Auto-generated method stub
  System.out.println(Thread.currentThread().getName()+" : recruted");
  
  countDownLatch.countDown();
 }

}

Explanation

The HRManger class created thre instances of TechLead's and starts them. The TechLead is a simple thread which waits for 2 sec and completes recruitment.
The HRManager also creates a CountDownLatch object with a parameter as '3'. This instance is passed to every TechLead instance. After every TechLead has
compeleted the recruitment techlead calls countDown() method on the shared CountDownLatch object.

The HRManager after starting the TechLead threads waits by calling awat() method on CountDownLatch instance. Only after countDown() is called 3 times the HRManager can proceed further.

That is he can distribute Offer Letters.
After running the HRManager class the output would be

HR Manager waiting for recruitment to complete...
first : recruted
third : recruted
second : recruted
Distribute Offer Letter

Important methods used

CountDownLatch.await() - When this method is called the current thread which called this method will go into waiting state and will wait until the count mentioned in countdownlatch becomes 0.
CountDownLatch.countDown() - When this method is called the int value passed to the countdownlatch decrements by 1. When the value becomes 0, the current Thread notifies the thread which has called await() on the same countdownlatch instance to wake up.

Some other Examples where countdownlatch could be used is when we distribute a file into fixed number of chunks and we send these chunk of data to different thread to process after all have done the processing then only the File should be closed.


Thread class  >>  Runnable Interface >>  Callable Interface   >>  CountDownLatch   >>  CyclicBarrier   >>  Semaphore   >>  Reentrant Lock   >>  Reentrant Lock with Condition

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Share the post