Friday, April 19, 2024
HomeJavaJava CountDownLatch Instance for Newcomers -

Java CountDownLatch Instance for Newcomers – [Multithreading Tutorial]


Hey Java programmers, the CountDownLatch is a vital concurrency utility class that was added in JDK 1.5 to facilitate inter-thread communication with out utilizing wait and notify strategies, however sadly, many Java builders nonetheless wrestle to grasp and use this highly effective device. On this article, you’ll be taught what’s CountDownLatch and the best way to use it to put in writing higher concurrent functions in Java. You need to use the CountDownLatch in case you are spawning a number of threads to do completely different jobs and wish to know when precisely all duties are completed to be able to transfer to the subsequent stage. In different phrases, you may block a thread till different threads full their process
One of many good examples the place you should use CountDownLatch is an software that downloads information from a database or one other software. For instance, we’re making a Java program to obtain all Udemy programs. Since Udemy has hundreds of programs, it’s worthwhile to create completely different threads to obtain completely different classes like know-how, growth, and so on.
Your software can solely be began as soon as all information is loaded and to know the standing of your loading progress you may create a CountDownLatch.

Suppose, you could have created 5 threads to load 5 completely different classes of knowledge then you may create a CountDownLatch with 5 counts after which convey down the depend by 1 when the loading of 1 class is completed. You are able to do this by calling the countDown() technique.

Since completely different threads will take completely different instances, your most important thread can wait till all threads have been accomplished and it will probably do by checking the remaining depend by calling the getCount() technique or simply calling the CountDownLatch.await() technique, which causes the present thread to attend till the latch has counted right down to zero or the thread is interrupted.

As soon as the depend turns into zero, it will probably announce that the applying is began and able to settle for consumer connections. So, you may see how helpful CountDownLatch will be in this sort of situation.

There are lots of different concurrency utilities in JDK that can make it easier to to put in writing subtle Java functions however If you’re new to Java and wrestle to grasp multi-threading and concurrency ideas like this, you may undergo a multithreading course like Multithreading and Parallel Computing in Java course from Udemy. It is an important course to be taught the multithreading fundamentals and grow to be a greater Java developer. 

1. CountDownLatch Instance in Java

Here’s a simplified model of Java Code for the above situation which demonstrates downloading information in a number of threads and utilizing CountDownLatch to examine completion. The necessary factor to notice right here is that we’re doing inter-thread communication with out utilizing the wait and notify technique in Java. 

Right here is the diagram as an example the purpose that how the primary thread waited till the depend reaches zero. In our instance, you may depend the entire variety of programs downloaded and print on the finish of this system. 

Java CountDownLatch Example for Beginners

Now, let’s examine the code to grasp the CountDownLatch a bit extra:

package deal device;

import java.util.concurrent.CountDownLatch;


public class CountDownLatchDemo {

  non-public static last CountDownLatch loadingLatch = new CountDownLatch(3);

  public static void most important(String args[]) {

    Thread pythonCourseLoader = new Thread("PythonCourseLoader") {

      @Override
      public void run() {
        System.out.println("Loading all Python programs from Udemy..");
        
        
        System.out.println("loading accomplished for Python programs");
        loadingLatch.countDown();
      }
    };

    Thread javaCourseLoader = new Thread("JavaCourseLoader") {
      @Override
      public void run() {
        System.out.println("Loading all Java programs from Udemy ..");
        
        strive {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          
          e.printStackTrace();
        }
        System.out.println("loading accomplished for Java programs");
        loadingLatch.countDown();
      }
    };

    Thread developmentCourseLoader = new Thread("developmentCourseLoader") {
      @Override
      public void run() {
        System.out.println("Loading all Develoment programs from Udemy ..");
        
        strive {
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          
          e.printStackTrace();
        }

        System.out.println("loading accomplished for growth programs");
        loadingLatch.countDown();
      }
    };

    pythonCourseLoader.begin();
    javaCourseLoader.begin();
    developmentCourseLoader.begin();

    whereas (loadingLatch.getCount() != 0) {
      
    }

    

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

Output:
Loading all Python programs from Udemy..
loading accomplished for Python programs
Loading all Improvement programs from Udemy ..
Loading all Java programs from Udemy ..
loading accomplished for Java programs
loading accomplished for growth programs
all completed.

On this program, now we have simply three threads. One to obtain all Python programs, the second to obtain all Java programs, and the third one to obtain all Improvement programs. 

I’ve created a CountDownLatch object with 3 counts as a static last variable:

CountDownLatch loadingLatch = new CountDownLatch(3);

After that, now we have three threads, which downloads information, in our case they do not do something simply sleep for 1, 2, and three seconds.

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

The most important() technique retains checking for remaining counts utilizing the getCount() technique and does no matter it desires to do solely when the depend reaches zero. Although I’ve used some time loop with getCount(), you may higher use latch.await() technique for ready.

An image is alleged to be price a thousand phrases, so I attempted to make this diagram to clarify the idea to you. On this diagram you may see that our most important thread is ready on CoutnDownLatch till all thread calls the countdown and depend reaches zero, after that, it progressed additional.

Briefly, the primary thread was blocked ready for different loader thread to complete their job.

Btw, If you’re not aware of important threading ideas like wait, notify, sleep, blocking, and so on, I counsel you first undergo Full Java Masterclass to be taught them.

Java CountDownLatch Example - When and How to Use It

2. CountDownLatch – Vital Factors

Now that you realize what’s CountDownLatch in Java and the best way to use it for inter-thread communication and synchronization. It is time to revise and keep in mind some necessary factors:

1. The CountDownLatch utility or class is simply out there on JRE 1.5 or later variations.

2. You can not reuse the latch as soon as the depend reaches zero. That is the primary distinction between a CyclicBarrier and CountDownLatch, which will be reused.

3. The getCount() technique returns the present depend i.e. remaining threads that haven’t completed but.

4. A thread can wait on the latch by calling the latch.await() technique to start out progress after the remaining thread finishes their process. Btw, if you wish to be taught threading and concurrency in depth and wish to write a high-performance java software then, I counsel you undergo Java Multithreading, Concurrency, and Efficiency Optimization course to be taught extra about efficiency optimization and writing strong concurrent code in Java

best course to learn multithreaing in Java

5. One of many easiest use of CountDownLatch class is to block a thread till different threads have completed their jobs.

In our instance, it was the primary thread that was blocked by calling the await() technique of CountDownLatch till all loader class completed their job i.e. downloaded programs from Udemy.

That is all about the best way to use CountDownLatch in Java. It is a helpful concurrency utility that can be utilized to maintain observe of the completion of duties completed by a number of threads. If you’re writing a Java software that hundreds information from one other system earlier than beginning functioning e.g. accepting consumer connections, you should use CountDownLatch to maintain observe of obtain duties.

 Different Java Multithreading and Concurrency Articles you could like

  • 5 Programs to Study Java Multithreading in-depth (programs)
  • High 5 Books to Grasp Concurrency in Java (books)
  • The way to do inter-thread communication in Java utilizing wait-notify? (reply)
  • Distinction between risky, synchronized, and atomic variable in Java (reply)
  • 10 Java Multithreading and Concurrency Finest Practices (article)
  • The way to pause a Thread in Java? (answer)
  • High 50 Multithreading and Concurrency Questions in Java (questions)
  • Distinction between CyclicBarrier and CountDownLatch in Java? (reply)
  • Understanding the stream of knowledge and code in Java program (reply)
  • The way to be part of two threads in Java? (reply)
  • The way to keep away from impasse in Java? (reply)
  • Distinction between Executor and ExecutorService in Java? (reply)
  • The way to cease a Thread in Java? (reply)
  • Distinction between ForkJoinPool and Executor Framework in Java(reply)
  • 5 Important Expertise to Crack Java Interviews (expertise)
  • What’s Occurs Earlier than in Java Concurrency? (reply)

Thanks loads for studying this text thus far. Should you like this CountDownLatch instance in Java then please share it with your folks and colleagues. When you have any questions or suggestions then please drop a notice.

P. S. – If you’re severe to enhance your Java Multithreading and Concurrency Expertise however in search of a free course to start out with then I additionally, counsel you take a look at this superior free Java Multithreading course
on Udemy. 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments