Here is a simple example of how and when to use CountDownLatch in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package concurrency; | |
import java.util.concurrent.CountDownLatch; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class CountdownLatchExample { | |
//In this example, our requirement is that main thread should wait till 3 child threads are done with their tasks | |
public static void main(String[] args) { | |
//Define a latch initialized with 3. | |
CountDownLatch latch = new CountDownLatch(3); | |
//Create a new thread pool with 3 threads. | |
ExecutorService executorService = Executors.newFixedThreadPool(3); | |
for (int i = 0; i < 3; i++) { | |
//Execute the runnable code using thread. | |
executorService.submit(new LatchTask(latch, "Thread_" + i)); | |
//Introduce some delay between each thread call. | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println("Waiting for threads to finish"); | |
//Main thread gets blocked here till all the latches are opened | |
try { | |
latch.await(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
executorService.shutdown(); | |
System.out.println("All threads are done"); | |
} | |
} | |
class LatchTask extends Thread { | |
CountDownLatch latch; | |
String threadName; | |
public LatchTask(CountDownLatch latch, String threadName) { | |
this.latch = latch; | |
this.threadName = threadName; | |
} | |
public void run() { | |
//Time consuming code. | |
System.out.println(threadName + " executing long running process"); | |
try { | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println(threadName + " opening latch"); | |
//Once done, thread opens the latch. | |
latch.countDown(); | |
System.out.println("Latches still on: " + latch.getCount()); | |
} | |
} | |
/* | |
Output: | |
Thread_0 executing long running process | |
Thread_1 executing long running process | |
Thread_2 executing long running process | |
Waiting for threads to finish | |
Thread_0 opening latch | |
Latches still on: 2 | |
Thread_1 opening latch | |
Latches still on: 1 | |
Thread_2 opening latch | |
Latches still on: 0 | |
All threads are done | |
*/ | |
Comments