Implementation of custom/own CountDownLatch in java - Detailed explanation with full program



Contents of page :
  • 1) Custom CountDownLatch in java?
  • 1.1) Custom CountDownLatch’s  constructor in java >
    • CountDownLatch(int count)  
    • CODE >
  • 1.2) Custom CountDownLatch’s await() method :
  • void await( ) throws InterruptedException
  • CODE >
  • 1.3) Custom CountDownLatch’s countDown() method :
  • void countDown( )
  • CODE >
  • 2) Custom CountDownLatch’s code in java >
  • 2.1) Program to demonstrate usage of Custom CountDownLatch in java >
  • 2.2) Let’s discuss output in detail, to get better understanding of Custom CountDownLatch usage in program >
  • 2.3) Occasionally, because of threads unpredictable behaviour output may be bit awkward >


1) Custom CountDownLatch in java?
In previous tutorial we read how to use  CountDownLatch in java. In this post we will be implementing custom CountDownLatch. This post intends you give you basic functionality of CountDownLatch using your own java code.


There might be situation where we might like our thread to wait until one or more threads completes certain operation.


A CountDownLatch is initialized with a given count .
count specifies the number of events that must occur before latch is released.
Every time a event happens count is reduced by 1. Once count reaches 0 latch is released.


1.1) Custom CountDownLatch’s  constructor in java >
  • CountDownLatch(int count)  
CountDownLatch is initialized with given count.
count specifies the number of events that must occur before latch is released.


CODE >
   public CountDownLatchCustom(int count) {
          this.count=count;
   }

1.2) Custom CountDownLatch’s await() method  in java:
  • void await( ) throws InterruptedException
Causes the current thread to wait until  one of the following things happens-
  • latch count has down to reached 0, or
  • unless the thread is interrupted.


CODE >
   public synchronized void await() throws InterruptedException {
          //If count is greater than 0, thread waits.
          if(count>0)
                 this.wait();
   }


1.3) Custom CountDownLatch’s countDown() method  in java:
  • void countDown( )
Reduces latch count by 1.
If count reaches 0, all waiting threads are released.


CODE >
   public synchronized void countDown() {
          //decrement the count by 1.
          count--;
         
          //If count is equal to 0, notify all waiting threads.
          if(count == 0)
                 this.notify();
   }


2) Custom CountDownLatch’s code in java >
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal .
* All Contents are copyrighted and must not be reproduced in any form.
   CountDownLatchCustom wait until one or more threads completes certain operation.
   A CountDownLatch is initialized with a given count .
   count specifies the number of events that must occur before
   latch is released.
   Every time a event happens count is reduced by 1. Once count
   reaches 0 latch is released.
*/
class CountDownLatchCustom{
   private int count;
   /**
   * CountDownLatch is initialized with given count.
   * count specifies the number of events that must occur
   * before latch is released.
   */
   public CountDownLatchCustom(int count) {
          this.count=count;
   }
   /**
   * Causes the current thread to wait until  one of the following things happens-
                 - latch count has down to reached 0, or
                 - unless the thread is interrupted.
   */
   public synchronized void await() throws InterruptedException {
          //If count is greater than 0, thread waits.
          if(count>0)
                 this.wait();
   }
   /**
   * Reduces latch count by 1.
   * If count reaches 0, all waiting threads are released.
   */
   public synchronized void countDown() {
          //decrement the count by 1.
          count--;
         
          //If count is equal to 0, notify all waiting threads.
          if(count == 0)
                 this.notify();
   }
  
}

2) Program to demonstrate usage of Custom CountDownLatch in java >
/**
* @author AnkitMittal
* Copyright (c), AnkitMittal .
* All Contents are copyrighted and must not be reproduced in any form.
   CountDownLatchCustom wait until one or more threads completes certain operation.
   A CountDownLatch is initialized with a given count .
   count specifies the number of events that must occur before
   latch is released.
   Every time a event happens count is reduced by 1. Once count
   reaches 0 latch is released.
*/
class CountDownLatchCustom{
   private int count;
   /**
   * CountDownLatch is initialized with given count.
   * count specifies the number of events that must occur
   * before latch is released.
   */
   public CountDownLatchCustom(int count) {
          this.count=count;
   }
   /**
   * Causes the current thread to wait until  one of the following things happens-
                 - latch count has down to reached 0, or
                 - unless the thread is interrupted.
   */
   public synchronized void await() throws InterruptedException {
          //If count is greater than 0, thread waits.
          if(count>0)
                 this.wait();
   }
   /**
   * Reduces latch count by 1.
   * If count reaches 0, all waiting threads are released.
   */
   public synchronized void countDown() {
          //decrement the count by 1.
          count--;
         
          //If count is equal to 0, notify all waiting threads.
          if(count == 0)
                 this.notify();
   }
  
}


/**
* Main class
*/
public class CountDownLatchCustomTest {
  
   public static void main(String[] args) {
          CountDownLatchCustom countDownLatchCustom=new CountDownLatchCustom(3);
          System.out.println("CountDownLatch has been created with count=3");
         
          new Thread(new MyRunnable(countDownLatchCustom),"Thread-1").start();
         
          try {
                 countDownLatchCustom.await();
          } catch (InterruptedException e) {
                 e.printStackTrace();
          }
         
          System.out.println("count has reached zero, "+
                       Thread.currentThread().getName()+" thread has ended");
   }
}


class MyRunnable implements Runnable{
  
   CountDownLatchCustom countDownLatchCustom;
  
   MyRunnable(CountDownLatchCustom countDownLatchCustom){
          this.countDownLatchCustom=countDownLatchCustom;
   }
  
   public void run(){
         
          for(int i=2;i>=0;i--){
                
                 countDownLatchCustom.countDown();           
                 System.out.println(Thread.currentThread().getName()+
                              " has reduced latch count to : "+ i);
                
                 try {
                       Thread.sleep(1000);
                 } catch (InterruptedException e) {
                       e.printStackTrace();
                 }
          }
                
   }
  
}
/*OUTPUT
CountDownLatch has been created with count=3
Thread-1 has reduced latch count to : 2
Thread-1 has reduced latch count to : 1
Thread-1 has reduced latch count to : 0
count has reached zero, main thread has ended
*/

2.1) Let’s discuss output in detail, to get better understanding of Custom CountDownLatch usage in program >
Note : I have mentioned output in green text.

CountDownLatch has been created with count=3
Initially, custom CountDownLatch is created with count=3
main thread called countDownLatchCustom.await() and it is waiting for count to become 0.
Thread-1 called countDownLatchCustom.countDown()  method. [Now, count=2]
Thread-1 has reduced latch count to : 2


Thread-1 called countDownLatchCustom.countDown()  method. [Now, count=1]
Thread-1 has reduced latch count to : 1


Thread-1 called countDownLatchCustom.countDown()  method. [Now, count=0]
Thread-1 has reduced latch count to : 0


count has reached zero, main thread has ended
As, count has reached zero, main thread has ended.



2.3) Occasionally, because of threads unpredictable behaviour output may be bit awkward in java >

/*OUTPUT
CountDownLatch has been created with count=3
Thread-1 has reduced latch count to : 2
Thread-1 has reduced latch count to : 1
count has reached zero, main thread has ended
Thread-1 has reduced latch count to : 0
*/


This may happen because as soon as count reaches 0 waiting threads are released. Here, as soon as Thread-1 called countDown() method third time main thread was released and its sysout statement was executed before Thread-1’s sysout statement.


Summary>
In previous tutorial we read how to use  CountDownLatch in java. In this post we learned how can we implement your own/custom CountDownLatch in thread concurrency in java. This post gave you basic functionality of CountDownLatch using your own java code.


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>


Executor and ExecutorService framework in java

Atomic operations in java

Semaphore in java

Implementation of custom/own Semaphore in java


eEdit
Must read for you :