Friday, November 1, 2019

Java Countdownlatch Representative - Multithreading Together With Concurrency Tutorial For Beginners

The CountDownLatch is an of import concurrency utility degree which was added inwards JDK 1.5 but unfortunately, many Java developers all the same scrap to empathize together with utilisation this powerful tool. You tin dismiss utilisation CountDownLatch if yous are spawning multiple threads to produce dissimilar jobs together with desire to know when just all tasks are finished so that yous tin dismiss motion to the adjacent stage. In other words, yous tin dismiss block a thread until other threads consummate their task. One of the skilful examples where yous tin dismiss utilisation CountDownLatch is an application which downloads information from a database or roughly other application. For example, nosotros are creating a Java plan to download all Udemy courses. Since Udemy has thousands of courses, yous create dissimilar threads to download dissimilar categories e.g. technology, development, etc.

Your application tin dismiss entirely endure started in ane lawsuit all information is loaded together with to know the condition of your loading progress yous tin dismiss create a CountDownLatch.

Suppose, yous conduct maintain created 5 threads to charge v dissimilar categories of information thus yous tin dismiss create a CountDownLatch amongst 5 counts together with thus convey downwards the count past times 1 when loading of ane category is finished. You tin dismiss produce this past times calling the countDown() method.

Since dissimilar thread volition select dissimilar time, your original thread tin dismiss wait until all threads conduct maintain completed together with it tin dismiss produce past times checking the remaining count past times calling getCount() method or simply calling the CountDownLatch.await() method, which causes electrical flow thread to hold off until the latch has counted downwards to zero or the thread is interrupted.

Once the count becomes zero, it tin dismiss denote that the application is started together with create to conduct maintain customer connections. So, yous tin dismiss run into how useful CountDownLatch tin dismiss endure inwards this variety of scenarios.

There are many other concurrency utilities inwards JDK which volition assist yous to write sophisticated Java application but If yous are novel to Java together with scrap agreement multi-threading together with concurrency concepts similar this, yous tin dismiss give-up the ghost through a comprehensive course of report like  Complete Java Masterclass to acquire them better.




1. CountDownLatch Example inwards Java

Here is a simplified version of Java Code for the higher upward 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 instance of CountDownLatch inwards Java  */ public class CountDownLatchDemo {    private static terminal 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 conduct maintain simply iii threads. One to download all Python courses, minute to download all Java courses together with the 3rd ane to download all Development courses.

I conduct maintain created a CountDownLatch object amongst 3 counts equally a static terminal variable:

CountDownLatch loadingLatch = new CountDownLatch(3);

After that, nosotros conduct maintain iii threads, which downloads data, inwards our instance they don't produce anything simply 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 give-up the ghost along checking for remaining counts using getCount() method together with produce whatever it wants to produce entirely when the count reaches zero. Though I conduct maintain used a spell loop amongst getCount(), yous tin dismiss ameliorate utilisation latch.await() method for waiting.

Influenza A virus subtype H5N1 movie is said to endure worth a chiliad words, thus I tried to brand this diagram to explicate the concept to you. In this diagram yous tin dismiss run into that our original thread is waiting on CoutnDownLatch until all thread calls the countdown together with count reaches zero, after that, it progressed further.

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

Btw, If yous are non familiar amongst essential threading concepts similar wait, notify, sleep, blocking, etc, I advise yous get-go give-up the ghost through Complete Java Masterclass to acquire them.


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



2. CountDownLatch - Important Points

Now that yous know what is CountDownLatch inwards Java together with how to utilisation it for inter-thread communication together with synchronization. It's fourth dimension to revise together with hollo back roughly of import points:

1. The CountDownLatch utility or degree is entirely available on JRE 1.5 or afterwards version.

2. You cannot reuse the latch in ane lawsuit the count reaches zero. This is the original deviation betwixt a CyclicBarrier together with CountDownLatch, which tin dismiss endure reused.

3. The getCount() method provide the electrical flow count i.e. remaining threads which conduct maintain non finished yet.

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

5. One of the simplest utilisation of CountDownLatch class is to block a thread until other threads conduct maintain finished their jobs.

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


That's all almost how to utilisation CountDownLatch inwards Java. It's a useful concurrency utility which tin dismiss endure used to give-up the ghost along rails of completion of tasks done past times multiple threads. If yous are writing a Java application which loads information from roughly other organisation earlier start performance e.g. accepting customer connections, yous tin dismiss utilisation CountDownLatch to give-up the ghost along rails 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 thus far. If yous similar this CountDownLatch instance thus delight percentage amongst your friends together with colleagues. If yous conduct maintain whatever questions or feedback thus delight driblet a note.

No comments:

Post a Comment