Monday, February 23, 2015

CountDownLatch in Java

CountDownLatch is a synchronizer that allows one or more threads to wait until a set of operations being performed in other threads completes. A CDL is initialized with a given count which specifies the number of parties involved. Whenever the method countDown() is called it decrements the value of count by one.

Generally a CDL is used when one or more threads are supposed to wait for a number of threads (parties) to finish. In that case waiting threads make use of await methods
which block until the count reaches zero, on other hand each party decrements the count whenever it finishes. When count is zero all waiting threads are released
and any subsequent invocations of await return immediately.



Unlike CyclicBarrier it is non-cyclic. If we need a version that resets the count then we should consider using a CyclicBarrier. A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

public class LatchBasicMain {

    static class Processor implements Runnable {
        CountDownLatch latch;

        public Processor(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            System.out.println("Started some work..");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            latch.countDown();
            System.out.println("Finished.");
        }
    }

    public static void main(String[] args) {
        int threadsCount = 5;
        CountDownLatch latch = new CountDownLatch(threadsCount);
        ExecutorService executorService = Executors.newFixedThreadPool(threadsCount);
        for(int i=0; i<threadsCount; i++) {
            executorService.submit(new Processor(latch));
        }

        // Main will wait for all other threads to finish.
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main Finished");
    }
}

I hope this post was informative.

No comments: