Java Countdownlatch Illustration - Multithreading Too Concurrency Tutorial For Beginners

The CountDownLatch is an of import concurrency utility aeroplane which was added inwards JDK 1.5 but unfortunately, many Java developers nevertheless combat to sympathize together with work this powerful tool. You tin work CountDownLatch if y'all are spawning multiple threads to practice unlike jobs together with desire to know when precisely all tasks are finished so that y'all tin motility to the side past times side stage. In other words, y'all tin block a thread until other threads consummate their task. One of the skillful examples where y'all tin work CountDownLatch is an application which downloads information from a database or closed to other application. For example, nosotros are creating a Java programme to download all Udemy courses. Since Udemy has thousands of courses, y'all practice unlike threads to download unlike categories e.g. technology, development, etc.

Your application tin solely live started ane time all information is loaded together with to know the condition of your loading progress y'all tin practice a CountDownLatch.

Suppose, y'all receive got created 5 threads to charge v unlike categories of information hence y'all tin practice a CountDownLatch amongst 5 counts together with hence convey downward the count past times 1 when loading of ane category is finished. You tin practice this past times calling the countDown() method.

Since unlike thread volition select unlike time, your primary thread tin wait until all threads receive got completed together with it tin practice past times checking the remaining count past times calling getCount() method or only calling the CountDownLatch.await() method, which causes electrical current thread to hold off until the latch has counted downward to zero or the thread is interrupted.

Once the count becomes zero, it tin denote that the application is started together with prepare to receive got customer connections. So, y'all tin run into how useful CountDownLatch tin live inwards this form of scenarios.

There are many other concurrency utilities inwards JDK which volition assist y'all to write sophisticated Java application but If y'all are novel to Java together with combat agreement multi-threading together with concurrency concepts similar this, y'all tin travel past times through a comprehensive course of written report like  Complete Java Masterclass to larn them better.




1. CountDownLatch Example inwards Java

Here is a simplified version of Java Code for the inwards a higher house scenario which demonstrates downloading information inwards multiple threads together with using CountDownLatch to cheque completion.

package tool;  import java.util.concurrent.CountDownLatch;  /**  *   * Influenza A virus subtype H5N1 uncomplicated illustration of CountDownLatch inwards Java  */ public class CountDownLatchDemo {    private static lastly 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, fourth dimension 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 grab 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 evolution courses ....         try {           Thread.sleep(2000);         } catch (InterruptedException e) {           // TODO Auto-generated grab block           e.printStackTrace();         }          System.out.println("loading completed for evolution 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 evolution courses all done. 


In this program, nosotros receive got only iii threads. One to download all Python courses, instant to download all Java courses together with the 3rd ane to download all Development courses.

I receive got created a CountDownLatch object amongst 3 counts every bit a static lastly variable:

CountDownLatch loadingLatch = new CountDownLatch(3);

After that, nosotros receive got iii threads, which downloads data, inwards our instance they don't practice anything only sleep for 1, 2, together with 3 seconds.

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

The main() method travel past times along checking for remaining counts using getCount() method together with practice whatever it wants to practice solely when the count reaches zero. Though I receive got used a piece loop amongst getCount(), y'all tin improve work latch.await() method for waiting.

Influenza A virus subtype H5N1 pic is said to live worth a thou words, hence I tried to brand this diagram to explicate the concept to you. In this diagram y'all tin run into that our primary thread is waiting on CoutnDownLatch until all thread calls the countdown together with count reaches zero, after that, it progressed further.

In short, the primary thread was blocked waiting for other loader thread to destination their job.

Btw, If y'all are non familiar amongst essential threading concepts similar wait, notify, sleep, blocking, etc, I propose y'all starting fourth dimension travel past times through Complete Java Masterclass to larn them.


 is an of import concurrency utility aeroplane which was added inwards JDK  Java CountDownLatch Example - Multithreading together with Concurrency Tutorial for Beginners



2. CountDownLatch - Important Points

Now that y'all know what is CountDownLatch inwards Java together with how to work it for inter-thread communication together with synchronization. It's fourth dimension to revise together with cry back closed to of import points:

1. The CountDownLatch utility or aeroplane is solely available on JRE 1.5 or afterwards version.

2. You cannot reuse the latch ane time the count reaches zero. This is the primary divergence betwixt a CyclicBarrier together with CountDownLatch, which tin live reused.

3. The getCount() method furnish the electrical current count i.e. remaining threads which receive got non finished yet.

4. Influenza A virus subtype H5N1 thread tin hold off on latch past times calling latch.await() method to start progress after remaining thread finishes their task. Btw, if y'all are novel to threading together with concurrency together with don't sympathize what is waiting for agency inwards the context of a thread, I propose y'all travel past times through Threading Essentials a  Mini-Course past times Java Champion Heinz Kabutz.

5. One of the simplest work of CountDownLatch class is to block a thread until other threads receive got finished their jobs.

In our example, it was the primary thread which was blocked past times calling the await() method of CountDownLatch until all loader aeroplane finished their chore i.e. downloaded courses from Udemy.


That's all close how to work CountDownLatch inwards Java. It's a useful concurrency utility which tin live used to travel past times along runway of completion of tasks done past times multiple threads. If y'all are writing a Java application which loads information from closed to other organization earlier start performance e.g. accepting customer connections, y'all tin work CountDownLatch to travel past times along runway of download tasks.


Further Learning
  1. Complete Java Masterclass
  2. Multithreading together with Parallel Computing inwards Java
  3. CountDownLatch Java Documentation


Thanks a lot for reading this article hence far. If y'all similar this CountDownLatch illustration hence delight portion amongst your friends together with colleagues. If y'all receive got whatsoever questions or feedback hence delight drib a note.

0 Response to "Java Countdownlatch Illustration - Multithreading Too Concurrency Tutorial For Beginners"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel