Wednesday, December 11, 2019

Java Countdownlatch Illustration - Concurrency Tutorial

CountDowaLatch is a high-level synchronization utility which is used to forestall a item thread to start processing until all threads are ready. This is achieved past times a countdown. The thread, which needs to hold off for starts amongst a counter, each thread them brand the count downward past times 1 when they acquire ready, i time the terminal thread telephone telephone countDown() method, in addition to thus the latch is broken in addition to the thread waiting amongst counter starts running. CountDownLatch is a useful synchronizer in addition to used heavily inwards multi-threaded testing. You tin role this shape to imitate really concurrent deportment i.e. trying to access something at the same fourth dimension i time every thread is ready. Worth noting is that CountDownLatch starts amongst a fixed publish of counts which cannot live changed later, though this restriction is re-mediated inwards Java vii past times introducing a similar but flexible concurrency utility called Phaser.

There is or thus other similar utility called CyclicBarrier, which tin likewise live used inwards this situation, where i thread needs to hold off for other threads earlier they start processing. Only deviation betwixt CyclicBarrier in addition to CountDownLatch is that yous tin reuse the barrier fifty-fifty after its broker but yous cannot reuse the count downward latch, i time count reaches to zero.

Mastering Concurrency is non slowly but if yous seriously wants to acquire an practiced Java programmer, yous got to tame this horse. One matter which tin attention yous inwards your journeying is the Brian Goetz classic, Java Concurrency inwards Practice. One of the most recommended majority for Java programmer.




How to role CountDownLatch inwards Java?

Theory is slowly to read but yous cannot empathise it until yous come across it alive inwards action, this is fifty-fifty to a greater extent than truthful amongst concurrency in addition to multi-threading. So let's come across how to role CountDownLatch inwards Java amongst a unproblematic demo. In this example, nosotros accept a main thread which is required to hold off until all worker thread finished their task. In lodge to accomplish this, I accept created a CountDownLatch amongst publish of count equal to 4, which is the total publish of worker threads. I in addition to thus passed this CountDownLatch to each worker thread, whenever they consummate their task, they telephone telephone countDown() method, i time terminal worker thread calls the countDown() method in addition to thus the latch is broken in addition to principal thread which has been waiting on latch start running i time again in addition to finished its execution.

level synchronization utility which is used to forestall a item thread to start proces Java CountDownLatch Example - Concurrency Tutorial


In lodge to really empathise this problem, yous kickoff demand to run past times by commenting latch.await() telephone telephone inwards principal method, without this telephone telephone principal thread volition non for whatsoever worker thread to complete their execution in addition to it volition terminate equally presently equally possible, may live fifty-fifty earlier whatsoever worker thread acquire started. If yous run i time again past times un-commenting latch.await() in addition to thus yous volition ever come across that principal thread has finished last. Why? because await() is a blocking call in addition to it blocks until count reaches zero.

Also, yous cannot reuse the latch i time count=0, calling await() method on latch volition accept no consequence i.e. thread volition non block, but they non throw whatsoever exception equally well, which is lilliputian chip of counter intuitive if yous are expecting an IllegalThreadStateException.

You tin likewise banking venture gibe Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to larn to a greater extent than nearly these higher score concurrency utilities introduced on Java 1.5 release.

level synchronization utility which is used to forestall a item thread to start proces Java CountDownLatch Example - Concurrency Tutorial


Here is the consummate programme in addition to code to role CountDownLatch inwards Java :

import java.util.concurrent.CountDownLatch;  /**  * Java Program to demonstrate how to role CountDownLatch, Its used when a thread  * needs to hold off for other threads earlier starting its work.  *   * @author Javin Paul  */ public class CountDownLatchDemo {      public static void main(String args[]) throws InterruptedException {                  CountDownLatch latch = new CountDownLatch(4);         Worker kickoff = new Worker(1000, latch, "WORKER-1");         Worker 2d = new Worker(2000, latch, "WORKER-2");         Worker 3rd = new Worker(3000, latch, "WORKER-3");         Worker 4th = new Worker(4000, latch, "WORKER-4");                  first.start();         second.start();         third.start();         fourth.start();                  // Main thread volition hold off until all thread finished         latch.await();                  System.out.println(Thread.currentThread().getName() + " has finished");      }  }  class Worker extends Thread {     private int delay;     private CountDownLatch latch;      public Worker(int delay, CountDownLatch latch, String name) {         super(name);         this.delay = delay;         this.latch = latch;     }      @Override     public void run() {         try {             Thread.sleep(delay);             latch.countDown();             System.out.println(Thread.currentThread().getName() + " has finished");         } catch (InterruptedException e) {             e.printStackTrace();         }     } }  Output WORKER-1 has finished WORKER-2 has finished WORKER-3 has finished WORKER-4 has finished principal has finished

If yous telephone telephone latch.await() again, after count reaches to zero, it volition non halt the principal thread again, neither it volition throw whatsoever Exception, it volition simply transcend through it, equally shown below :

// Main thread volition hold off until all thread finished latch.await();          System.out.println(Thread.currentThread().getName() + " has started running again");          latch.await(); System.out.println(Thread.currentThread().getName() + " has finished");  Output principal has started running i time again principal has finished

This is where CountDownLatch is dissimilar than CyclicBarrier because yous tin reuse the barrier to halt the thread fifty-fifty after barrier is broken.



Important points nearly CountDownLatch inwards Java

Let's revisit or thus of import things nearly CountDownLatch inwards Java. This volition attention yous to retain the noesis yous accept simply learned :

1) When yous do an object of CountDownLatch yous transcend an int to its constructor (the count), this is really publish of invited parties (threads) for an event.

2) The thread, which is subject on other threads to start processing, waits on latch until every other thread has called count down. All threads, which are waiting on await() continue together i time count downward reaches to zero.

3) countDown() method decrements the count in addition to await() method blocks until count == 0

4) Once count reaches to zero, countdown latch cannot live used again, calling await() method on that latch volition non halt whatsoever thread, but it volition neither throw whatsoever exception.

5) One of the pop role of CountDownLatch is inwards testing concurrent code, past times using this latch yous tin guarantee that multiple threads are firing asking simultaneously or executing code at almost same time.

6) There is a similar concurrency utility called CyclicBarrier, which tin likewise role to imitate this scenario but deviation betwixt CountDownLatch in addition to CyclicBarrier is that yous tin reuse the cyclic barrier i time the barrier is broken but yous cannot reuse the CountDownLatch i count reaches to zero.

7) Java vii likewise introduced a flexible choice of CountDownLatch, known equally Phaser. It likewise has publish of unarrived political party simply similar barrier in addition to latch but that publish is flexible. So its to a greater extent than similar yous volition non block if i of the invitee bunks the party.


That's all inwards this Java CountDownLatch example. In this tutorial, yous accept learned how to role CountDownLatch inwards Java to brand certain your telephone commutation thread starts processing i time all pre-conditions are full-filled or when all threads are ready. There are 2 other similar utility, i is called Phaser in addition to other is called CyclicBarrier, if yous desire a dynamic count, dice for Phaser in addition to if yous desire to reuse the barrier i time again in addition to again, dice for CyclicBarrier. We volition come across examples of this 2 synchronizers inwards Java inwards our adjacent Java Concurrency tutorial.

Recommended resources for farther learning :
  • Java documentation of CountDownLatch (documentation)
  • Java Concurrency inwards Practice past times Brian Goetz (the book)
  • The Art of Multiprocessor Programming past times Maurice Herlihy  (the book)

No comments:

Post a Comment