top of page
Search
Writer's pictureAbhinaw Tripathi

CountDownLatch in java example


CountDownLatch in Java: It is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started. Working of CountDownLatch: When we create an object of CountDownLatch, we specify the number if threads it should wait for, all such thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. As soon as count reaches zero, the waiting task starts running. Sample Code: import java.util.concurrent.CountDownLatch; /** * */ /** * @author Abhinaw.Tripathi * */ public class CountDownLatchApp { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub CountDownLatch latch=new CountDownLatch(7); Worker worker1=new Worker(1000, latch, "Worker-1"); Worker worker2=new Worker(1000, latch, "Worker-2"); Worker worker3=new Worker(1000, latch, "Worker-3"); Worker worker4=new Worker(1000, latch, "Worker-4"); Worker worker5=new Worker(1000, latch, "Worker-5"); Worker worker6=new Worker(1000, latch, "Worker-6"); Worker worker7=new Worker(1000, latch, "Worker-7"); worker1.start(); worker2.start(); worker3.start(); worker4.start(); worker5.start(); worker6.start(); worker7.start(); latch.await(); System.out.println(Thread.currentThread().getName() + "has finished."); } } class Worker extends Thread { private int delay; private CountDownLatch countDownLatch; public Worker(int delay,CountDownLatch countDownLatch,String name) { super(name); this.countDownLatch=countDownLatch; this.delay=delay; } public void run() { try { Thread.sleep(delay); countDownLatch.countDown(); System.out.println(Thread.currentThread().getName() + "Finished"); } catch(Exception e) { e.printStackTrace(); } } } Output: Worker-1Finished Worker-3Finished Worker-7Finished Worker-4Finished Worker-5Finished Worker-6Finished Worker-2Finished mainhas finished. Important Points about CountDownLatch: Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually number of invited parties (threads) for an event. The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero. countDown() method decrements the count and await() method blocks until count == 0


9 views0 comments

Recent Posts

See All
bottom of page