CountDowaLatch is a high-level synchronization utility which is used to foreclose 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 cash inward one's chips ready, i time the final thread telephone telephone countDown() method, together with then the latch is broken together with the thread waiting amongst counter starts running. CountDownLatch is a useful synchronizer together with used heavily inward multi-threaded testing. You tin purpose this shape to copy really concurrent demeanor 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 expose of counts which cannot live changed later, though this restriction is re-mediated inward Java seven past times introducing a similar but flexible concurrency utility called Phaser.
There is around other similar utility called CyclicBarrier, which tin likewise live used inward this situation, where i thread needs to hold off for other threads earlier they start processing. Only divergence betwixt CyclicBarrier together with CountDownLatch is that you lot tin reuse the barrier fifty-fifty after its broker but you lot cannot reuse the count downward latch, i time count reaches to zero.
Mastering Concurrency is non tardily but if you lot seriously wants to cash inward one's chips an goodness Java programmer, you lot got to tame this horse. One matter which tin help you lot inward your journeying is the Brian Goetz classic, Java Concurrency inward Practice. One of the most recommended mass for Java programmer.
In lodge to really empathize this problem, you lot source demand to run past times by commenting latch.await() telephone telephone inward primary method, without this telephone telephone primary thread volition non for whatever worker thread to complete their execution together with it volition terminate equally presently equally possible, may live fifty-fifty earlier whatever worker thread acquire started. If you lot run i time to a greater extent than past times un-commenting latch.await() together with then you lot volition ever come across that primary thread has finished last. Why? because await() is a blocking call together with it blocks until count reaches zero.
Also, you lot cannot reuse the latch i time count=0, calling await() method on latch volition accept no lawsuit i.e. thread volition non block, but they non throw whatever exception equally well, which is piffling fight of counter intuitive if you lot are expecting an IllegalThreadStateException.
You tin likewise banking venture represent Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to acquire to a greater extent than virtually these higher score concurrency utilities introduced on Java 1.5 release.
Here is the consummate programme together with code to purpose CountDownLatch inward Java :
If you lot telephone telephone latch.await() again, after count reaches to zero, it volition non halt the primary thread again, neither it volition throw whatever Exception, it volition but overstep through it, equally shown below :
This is where CountDownLatch is dissimilar than CyclicBarrier because you lot tin reuse the barrier to halt the thread fifty-fifty after barrier is broken.
1) When you lot practise an object of CountDownLatch you lot overstep an int to its constructor (the count), this is really expose 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() cash inward one's chips on together i time count downward reaches to zero.
3) countDown() method decrements the count together with 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 whatever thread, but it volition neither throw whatever exception.
5) One of the pop purpose of CountDownLatch is inward testing concurrent code, past times using this latch you lot 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 purpose to copy this scenario but divergence betwixt CountDownLatch together with CyclicBarrier is that you lot tin reuse the cyclic barrier i time the barrier is broken but you lot cannot reuse the CountDownLatch i count reaches to zero.
7) Java seven likewise introduced a flexible option of CountDownLatch, known equally Phaser. It likewise has expose of unarrived political party but similar barrier together with latch but that expose is flexible. So its to a greater extent than similar you lot volition non block if i of the invitee bunks the party.
That's all inward this Java CountDownLatch example. In this tutorial, you lot accept learned how to purpose CountDownLatch inward Java to brand certain your primal 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 together with other is called CyclicBarrier, if you lot desire a dynamic count, cash inward one's chips for Phaser together with if you lot desire to reuse the barrier i time to a greater extent than together with again, cash inward one's chips for CyclicBarrier. We volition come across examples of this 2 synchronizers inward Java inward our adjacent Java Concurrency tutorial.
Recommended resources for farther learning :
There is around other similar utility called CyclicBarrier, which tin likewise live used inward this situation, where i thread needs to hold off for other threads earlier they start processing. Only divergence betwixt CyclicBarrier together with CountDownLatch is that you lot tin reuse the barrier fifty-fifty after its broker but you lot cannot reuse the count downward latch, i time count reaches to zero.
Mastering Concurrency is non tardily but if you lot seriously wants to cash inward one's chips an goodness Java programmer, you lot got to tame this horse. One matter which tin help you lot inward your journeying is the Brian Goetz classic, Java Concurrency inward Practice. One of the most recommended mass for Java programmer.
How to purpose CountDownLatch inward Java?
Theory is tardily to read but you lot cannot empathize it until you lot come across it alive inward action, this is fifty-fifty to a greater extent than truthful amongst concurrency together with multi-threading. So let's come across how to purpose CountDownLatch inward 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 attain this, I accept created a CountDownLatch amongst expose of count equal to 4, which is the total expose of worker threads. I together with then passed this CountDownLatch to each worker thread, whenever they consummate their task, they telephone telephone countDown() method, i time final worker thread calls the countDown() method together with then the latch is broken together with primary thread which has been waiting on latch start running i time to a greater extent than together with finished its execution.In lodge to really empathize this problem, you lot source demand to run past times by commenting latch.await() telephone telephone inward primary method, without this telephone telephone primary thread volition non for whatever worker thread to complete their execution together with it volition terminate equally presently equally possible, may live fifty-fifty earlier whatever worker thread acquire started. If you lot run i time to a greater extent than past times un-commenting latch.await() together with then you lot volition ever come across that primary thread has finished last. Why? because await() is a blocking call together with it blocks until count reaches zero.
Also, you lot cannot reuse the latch i time count=0, calling await() method on latch volition accept no lawsuit i.e. thread volition non block, but they non throw whatever exception equally well, which is piffling fight of counter intuitive if you lot are expecting an IllegalThreadStateException.
You tin likewise banking venture represent Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to acquire to a greater extent than virtually these higher score concurrency utilities introduced on Java 1.5 release.
Here is the consummate programme together with code to purpose CountDownLatch inward Java :
import java.util.concurrent.CountDownLatch; /** * Java Program to demonstrate how to purpose 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 source = new Worker(1000, latch, "WORKER-1"); Worker minute = 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 primary has finished
If you lot telephone telephone latch.await() again, after count reaches to zero, it volition non halt the primary thread again, neither it volition throw whatever Exception, it volition but overstep 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 primary has started running i time to a greater extent than primary has finished
This is where CountDownLatch is dissimilar than CyclicBarrier because you lot tin reuse the barrier to halt the thread fifty-fifty after barrier is broken.
Important points virtually CountDownLatch inward Java
Let's revisit around of import things virtually CountDownLatch inward Java. This volition help you lot to retain the noesis you lot accept but learned :1) When you lot practise an object of CountDownLatch you lot overstep an int to its constructor (the count), this is really expose 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() cash inward one's chips on together i time count downward reaches to zero.
3) countDown() method decrements the count together with 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 whatever thread, but it volition neither throw whatever exception.
5) One of the pop purpose of CountDownLatch is inward testing concurrent code, past times using this latch you lot 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 purpose to copy this scenario but divergence betwixt CountDownLatch together with CyclicBarrier is that you lot tin reuse the cyclic barrier i time the barrier is broken but you lot cannot reuse the CountDownLatch i count reaches to zero.
7) Java seven likewise introduced a flexible option of CountDownLatch, known equally Phaser. It likewise has expose of unarrived political party but similar barrier together with latch but that expose is flexible. So its to a greater extent than similar you lot volition non block if i of the invitee bunks the party.
That's all inward this Java CountDownLatch example. In this tutorial, you lot accept learned how to purpose CountDownLatch inward Java to brand certain your primal 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 together with other is called CyclicBarrier, if you lot desire a dynamic count, cash inward one's chips for Phaser together with if you lot desire to reuse the barrier i time to a greater extent than together with again, cash inward one's chips for CyclicBarrier. We volition come across examples of this 2 synchronizers inward Java inward our adjacent Java Concurrency tutorial.
Recommended resources for farther learning :
- Java documentation of CountDownLatch (documentation)
- Java Concurrency inward Practice past times Brian Goetz (the book)
- The Art of Multiprocessor Programming past times Maurice Herlihy (the book)
0 Response to "Java CountDownLatch Example"
Posting Komentar