Saturday, August 5, 2017

CountDownLatch alike join() in java


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

Ø  CountDownLatch also allows flexibility on number of thread for which main thread should wait, It can wait for one thread or n number of thread, there is not much change on code.


  Ø  Also, to use join(), each thread should have a reference to another thread to call join(). It makes your code a bit dirty especially when you have more than 2 working threads. Sharing of one instance of CountDownLatch/CyclicBarrier looks more clear.

  Ø  CountDownLatch works in latch principle, main thread will wait until Gate is open. One thread waits for n number of threads specified while creating CountDownLatch in Java. Any thread, usually main thread of application, which calls CountDownLatch.await() will wait until count reaches zero or its interrupted by another Thread. All other thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. as soon as count reaches zero, Thread awaiting starts running.

  Ø  Use CountDownLatch when one of Thread like main thread, require to wait for one or more thread to complete, before its start doing processing. 

  Ø  You can not reuse CountDownLatch once count is reaches to zero

  Ø  Main Thread wait on Latch by calling CountDownLatch.await() method while other thread calls CountDownLatch.countDown() to inform that they have completed.

Below Java program requires 3 services namely CacheServiceAlertService  and ValidationService  to be started and ready before application can handle any request and this is achieved by using CountDownLatch in Java.

package com.concurrent.jdk5;

import java.util.concurrent.CountDownLatch;

/*Use CountDownLatch when one of Thread like main thread,
  require to wait for one or more thread to complete, before its start doing processing.
*/
public class CountDownLatchImpl {

     public static void main(String[] args) throws InterruptedException {
          
           /*Since 3 is shared to all threads, it must be a volatile */
           final CountDownLatch latch = new CountDownLatch(3);
    
           /* Instantiating three services along with latch */
           Thread cacheService = new Thread(new Service("CacheService",1000,latch));
           Thread alertService = new Thread(new Service("AlertService",3000,latch));
           Thread validationService = new Thread(new Service("ValidationService",5000,latch));
    
           /* Starting all threads at once */
           cacheService.start();
           alertService.start();
           validationService.start();
          
/*Application should not start processing any thread until all  service is up and ready to do there job.Countdown latch is idle choice here, main thread will start with count 3 and wait until count reaches zero. Each thread once up and read will do a count down. this will ensure that main thread is not started processing until all services is up.Causes the current thread to wait until the latch has counted down to zero */

           latch.await();
           System.out.println("All services are up, Application is starting now");
     }
}

class Service implements Runnable {
     private final String name;
     private final long timeToStart;
     private final CountDownLatch latch;

     public Service(String name, long timeToStart, CountDownLatch latch) {
           this.name = name;
           this.timeToStart = timeToStart;
           this.latch = latch;
     }

     public void run() {
          
           System.out.println(name + "Starts");
           try {
                Thread.sleep(timeToStart);
           } catch (InterruptedException ex) {
           }
           System.out.println(name + " is Up");
          
           /* reduce count of CountDownLatch by 1 */
           latch.countDown();
     }
}

Output

AlertServiceStarts
ValidationServiceStarts
CacheServiceStarts
CacheService is Up
AlertService is Up
ValidationService is Up
All services are up, Application is starting now


No comments:

Post a Comment