CountDownLatch Introduction
CountDownLatch is a synchronization object that allows a thread to wait till certain events occur in other threads. We can make the current thread to wait until few dependent threads have completed their operation. CountDownLatch starts with a initial count. Thread that needs to wait, blocks until the count reaches to zero. Dependent threads on completing their task start to count down after which all the blocked threads are released.Java CountDownLatch Class
Java supports CountDownLatch synchronization object. Some of the key APIs of CountDownLatch class are listed below.- CountDownLatch(int count) - Constructor that creates CountDownLatch with a specified count.
- void await() - Current threads waits till the latch has counted down to zero
- boolean await(long timeout, TimeUnit unit) - Causes the current thread to wait till the latch has counted down to zero or the specified timeout has occurred.
- void countDown() - Decrements the latch count. Releases waiting threads on count reaching zero.
Java CountDownLatch Example
In this example, we create a CountDownLatch object with initial count of two. The main thread creates pre-processing threads and awaits for them to be completed. Once the pre-processing threads complete their tasks they decrement the latch count. Once the latch reaches count of zero then the main thread is released and proceeds to completion.package cdl; import java.util.concurrent.CountDownLatch; public class CDLExample { private static class PreProcess1 implements Runnable { CountDownLatch cdl = null; PreProcess1(CountDownLatch cdl) { this.cdl = cdl; } @Override public void run() { System.out.println("Preprocess1 done"); cdl.countDown(); } } private static class PreProcess2 implements Runnable { CountDownLatch cdl = null; PreProcess2(CountDownLatch cdl) { this.cdl = cdl; } @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Preprocess2 done"); cdl.countDown(); } } public static void main(String[] args) { CountDownLatch cdl = new CountDownLatch(2); try { new Thread(new PreProcess1(cdl)).start(); new Thread(new PreProcess2(cdl)).start(); System.out.println("Waiting ..."); cdl.await(); System.out.println("Completed ..."); } catch (InterruptedException e) { e.printStackTrace(); } } }This program produces the following output.
Waiting ... Preprocess1 done Preprocess2 done Completed ...Read other concurrency tutorials from Java Tutorials page.
0 comments:
Post a Comment