UrbanPro
true

Learn Advanced Java coaching from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Java Concurrency Model - CountDownLatch

Somenath Mukhopadhyay
04/04/2017 0 0

What is CountDownLatch in Java?

CountDownLatch in Java is a kind of synchronizer which allows one Thread to wait for one or more Threads before starts processing. This is very crucial requirement and often needed in server side core Java application and having this functionality built-in as CountDownLatch greatly simplifies the development. CountDownLatch in Java is introduced on Java 5 along with other concurrent utilities like CyclicBarrier, Semaphore, ConcurrentHashMap and BlockingQueue in java.util.concurrent package. In this Java concurrency tutorial we will learn what is CountDownLatch in Java, How CountDownLatch works in Java, an example of CountDownLatch in Java and finally some worth noting points about this concurrent utility. You can also implement same functionality using wait and notify mechanism in Java but it requires lot of code and getting it write in first attempt is tricky,  With CountDownLatch it can  be done in just few lines. 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.

Class CountDownLatch Demo 

package com.somitsolutions.training.java.ExperimentationWithCountdownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CountDownLatchDemo {

   public static void main(String args[]) {
      final CountDownLatch latch = new CountDownLatch(3);
      Thread service1 = new Thread(new Service("Service1", 1000, latch));
      Thread service2 = new Thread(new Service("Service2", 1000, latch));
      Thread service3 = new Thread(new Service("Service3", 1000, latch));
     
      service1.start();

      service2.start();

      service3.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.
     
      //count is 3 since we have 3 Threads (Services)
     
      try{
           latch.await();  //main thread is waiting on CountDownLatch to finish
           System.out.println("All services are up, Application is starting now");
      }catch(InterruptedException ie){
          ie.printStackTrace();
      }
     
   }
 
}

/**
* Service class which will be executed by Thread using CountDownLatch synchronizer.
*/
class Service implements Runnable{
   private final String name;
   private final int timeToStart;
   private final CountDownLatch latch;
 
   public Service(String name, int timeToStart, CountDownLatch latch){
       this.name = name;
       this.timeToStart = timeToStart;
       this.latch = latch;
   }
 
   @Override
   public void run() {
       try {

//Do all the processing. Here we have just made the thread sleep
           Thread.sleep(timeToStart);
       } catch (InterruptedException ex) {
           Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
       }
       System.out.println(

0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

Java Concurrency Model - Future Task...
Callables and Future The FiutureTask is "A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the...

Copy-on-Write
Note: You can read the original write-up at http://som-itsolutions.blogspot.in/2017/01/copy-on-write.html As i was trying to recapitulate several important concepts of OOAD, naturally COW or Copy-On-Write...

Implementation of a state machine for a long running background task in Android
In the below example I will show how we can break a long-running background task running in a service into different states of a state machine and notify the front end UI about each and every stage as...

Callback using Function Pointer (in C), interface (in Java) and EventListener pattern
Note : Read the original document at http://som-itsolutions.blogspot.in/2017/01/blog-post_24.html “In computer programming, a callback is a reference to executable code, or a piece of executable...

Observer Pattern in Java.
As I was going through the different source code files of the Java Util package, I found the implementation of the Observer Pattern ( see the Gang of Four books for more information on this pattern) in...
X

Looking for Advanced Java coaching Classes?

The best tutors for Advanced Java coaching Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Advanced Java coaching with the Best Tutors

The best Tutors for Advanced Java coaching Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more