Java CountDownLatch Example for Beginners - [Multithreading Tutorial]

Hello Java programmers, the CountDownLatch is an important concurrency utility class that was added in JDK 1.5 to facilitate inter-thread communication without using wait and notify methods, but unfortunately, many Java developers still struggle to understand and use this powerful tool. In this article, you will learn what is CountDownLatch and how to use it to write better concurrent applications in Java. You can use the CountDownLatch if you are spawning multiple threads to do different jobs and want to know when exactly all tasks are finished so that you can move to the next stage. In other words, you can block a thread until other threads complete their task

One of the good examples where you can use CountDownLatch is an application that downloads data from a database or another application. For example, we are creating a Java program to download all Udemy courses. Since Udemy has thousands of courses, you need to create different threads to download different categories like technology, development, etc.

Your application can only be started once all data is loaded and to know the status of your loading progress you can create a CountDownLatch.

Suppose, you have created 5 threads to load five different categories of data then you can create a CountDownLatch with 5 counts and then bring down the count by 1 when the loading of one category is finished. You can do this by calling the countDown() method.

Since different threads will take different times, your main thread can wait until all threads have been completed and it can do by checking the remaining count by calling the getCount() method or just calling the CountDownLatch.await() method, which causes the current thread to wait until the latch has counted down to zero or the thread is interrupted.

Once the count becomes zero, it can announce that the application is started and ready to accept client connections. So, you can see how useful CountDownLatch can be in this kind of scenario.

There are many other concurrency utilities in JDK that will help you to write sophisticated Java applications but If you are new to Java and struggle to understand multi-threading and concurrency concepts like this, you can go through a multithreading course like Multithreading and Parallel Computing in Java course from Udemy. It's a great course to learn the multithreading basics and become a better Java developer. 



1. CountDownLatch Example in Java

Here is a simplified version of Java Code for the above scenario which demonstrates downloading data in multiple threads and using CountDownLatch to check completion. The important thing to note here is that we are doing inter-thread communication without using the wait and notify method in Java. 

Here is the diagram to illustrate the point that how the main thread waited until the count reaches zero. In our example, you can count the total number of courses downloaded and print at the end of the program. 

Java CountDownLatch Example for Beginners


Now, let's see the code to understand the CountDownLatch a bit more:
package tool;

import java.util.concurrent.CountDownLatch;

/**
  * A simple example of CountDownLatch in Java
 */
public class CountDownLatchDemo {

  private static final CountDownLatch loadingLatch = new CountDownLatch(3);

  public static void main(String args[]) {

    Thread pythonCourseLoader = new Thread("PythonCourseLoader") {

      @Override
      public void run() {
        System.out.println("Loading all Python courses from Udemy..");
        // loading Python courses ....
        // loading completed, time to count down
        System.out.println("loading completed for Python courses");
        loadingLatch.countDown();
      }
    };

    Thread javaCourseLoader = new Thread("JavaCourseLoader") {
      @Override
      public void run() {
        System.out.println("Loading all Java courses from Udemy ..");
        // loading Java courses ....
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println("loading completed for Java courses");
        loadingLatch.countDown();
      }
    };

    Thread developmentCourseLoader = new Thread("developmentCourseLoader") {
      @Override
      public void run() {
        System.out.println("Loading all Develoment courses from Udemy ..");
        // loading development courses ....
        try {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        System.out.println("loading completed for development courses");
        loadingLatch.countDown();
      }
    };

    pythonCourseLoader.start();
    javaCourseLoader.start();
    developmentCourseLoader.start();

    while (loadingLatch.getCount() != 0) {
      // wait
    }

    // loadingLatch.await();

    System.out.println("all done.");
  }
}

Output:
Loading all Python courses from Udemy..
loading completed for Python courses
Loading all Development courses from Udemy ..
Loading all Java courses from Udemy ..
loading completed for Java courses
loading completed for development courses
all done.
In this program, we have just three threads. One to download all Python courses, the second to download all Java courses, and the third one to download all Development courses. 

I have created a CountDownLatch object with 3 counts as a static final variable:
CountDownLatch loadingLatch = new CountDownLatch(3);
After that, we have three threads, which downloads data, in our case they don't do anything just sleep for 1, 2, and 3 seconds.

Every time a thread completes its execution it calls the countDown() method on the loadingLatch object.

The main() method keeps checking for remaining counts using the getCount() method and does whatever it wants to do only when the count reaches zero. Though I have used a while loop with getCount(), you can better use latch.await() method for waiting.

A picture is said to be worth a thousand words, so I tried to make this diagram to explain the concept to you. In this diagram you can see that our main thread is waiting on CoutnDownLatch until all thread calls the countdown and count reaches zero, after that, it progressed further.

In short, the main thread was blocked waiting for other loader thread to finish their job.

Btw, If you are not familiar with essential threading concepts like wait, notify, sleep, blocking, etc, I suggest you first go through Complete Java Masterclass to learn them.


Java CountDownLatch Example - When and How to Use It



2. CountDownLatch - Important Points

Now that you know what is CountDownLatch in Java and how to use it for inter-thread communication and synchronization. It's time to revise and remember some important points:

1. The CountDownLatch utility or class is only available on JRE 1.5 or later versions.

2. You cannot reuse the latch once the count reaches zero. This is the main difference between a CyclicBarrier and CountDownLatch, which can be reused.

3. The getCount() method returns the current count i.e. remaining threads that have not finished yet.

4. A thread can wait on the latch by calling the latch.await() method to start progress after the remaining thread finishes their task. Btw, if you want to learn threading and concurrency in depth and want to write a high-performance java application then, I suggest you go through Java Multithreading, Concurrency, and Performance Optimization course to learn more about performance optimization and writing solid concurrent code in Java

best course to learn multithreaing in Java



5. One of the simplest use of CountDownLatch class is to block a thread until other threads have finished their jobs.

In our example, it was the main thread that was blocked by calling the await() method of CountDownLatch until all loader class finished their job i.e. downloaded courses from Udemy.


That's all about how to use CountDownLatch in Java. It's a useful concurrency utility that can be used to keep track of the completion of tasks done by multiple threads. If you are writing a Java application that loads data from another system before starting functioning e.g. accepting client connections, you can use CountDownLatch to keep track of download tasks.

 Other Java Multithreading and Concurrency Articles you may like
  • 5 Courses to Learn Java Multithreading in-depth (courses)
  • Top 5 Books to Master Concurrency in Java (books)
  • How to do inter-thread communication in Java using wait-notify? (answer)
  • Difference between volatile, synchronized, and atomic variable in Java (answer)
  • 10 Java Multithreading and Concurrency Best Practices (article)
  • How to pause a Thread in Java? (solution)
  • Top 50 Multithreading and Concurrency Questions in Java (questions)
  • Difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • Understanding the flow of data and code in Java program (answer)
  • How to join two threads in Java? (answer)
  • How to avoid deadlock in Java? (answer)
  • Difference between Executor and ExecutorService in Java? (answer)
  • How to stop a Thread in Java? (answer)
  • Difference between ForkJoinPool and Executor Framework in Java(answer)
  • 5 Essential Skills to Crack Java Interviews (skills)
  • What is Happens Before in Java Concurrency? (answer)

Thanks a lot for reading this article so far. If you like this CountDownLatch example in Java then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious to improve your Java Multithreading and Concurrency Skills but looking for a free course to start with then I also, suggest you check out this awesome free Java Multithreading course on Udemy. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.