java.util.concurrent.CountDownLatch Example
In this example we will see how and when to use java.util.concurrent.CountDownLatch
CountDownLatch
is used in synchronisation to allow one or more threads to wait until a set of operations being performed in other threads completes.
For Example, it can be used when a Thread has to wait until few dependent threads have started. CountDownLatch
is initialised with a given count. This count is decremented by calls to the countDown() method. Each Thread on whose completion the main Thread is waiting will call countDown() method and decrease the count. Once all such threads are executed the count will become 0 and then the waiting main thread can start its execution.
Lets see its working in an example:
JavaCountDownLatchExample.java
package com.jcg.example; import java.util.concurrent.CountDownLatch; /** * * @author anirudh * */ public class JavaCountDownLatchExample { public static void main(String[] args) { // intialising count down latch by 2, as it will wait for 2 threads to // finish execution final CountDownLatch latch = new CountDownLatch(2); // making two threads for 2 services Thread serviceOneThread = new Thread(new ServiceOne(latch)); Thread serviceTwoThread = new Thread(new ServiceTwo(latch)); serviceOneThread.start(); serviceTwoThread.start(); // latch waits till the count becomes 0 // this way we can make sure that the execution of main thread only // finishes ones 2 services have executed try { latch.await(); System.out.println("Starting main Thread!!!"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Output:
started service Two Started service One Starting main Thread!!!
As we can see in the output that the main thread’s execution waited until service One and Service Two Threads have been completed.
Let us also see the code for ServiceOne and ServiceTwo classes :
ServiceOne.java
package com.jcg.example; import java.util.concurrent.CountDownLatch; /** * * @author anirudh * */ public class ServiceOne implements Runnable{ private final CountDownLatch latch; public ServiceOne(CountDownLatch latch) { this.latch = latch; } @Override public void run() { System.out.println("Started service One"); //reduce count of Count Down Latch by 1. latch.countDown(); } }
ServiceTwo.java
package com.jcg.example; import java.util.concurrent.CountDownLatch; /** * * @author anirudh * */ public class ServiceTwo implements Runnable{ private final CountDownLatch latch; public ServiceTwo(CountDownLatch latch) { this.latch = latch; } @Override public void run() { System.out.println("started service Two"); latch.countDown(); } }
In the example above we saw how we can use CountDownLatch to make sure that a thread stays in wait state until other threads have finished execution.
Download Source Code
So, In this example we saw how we can use CountDownLatch
in Java.
You can download the full source code of this example here : JavaCountDownLatchExample.zip