Thursday, March 20, 2008

Java Concurrent Programming : CountDownLatch

CountDownLatch in the concurrent programming framework provided by java is pretty cool.
In principle it works like a binary latch . (Once set it remain in that state for ever )

So when would something like a countdownlatch be useful for thread programming .

Consider a scenario , you have a big task T to be done by N threads .

1) Now you want all the threads to be started at the same time so that they get equal opportunity
to participate in the completion of the task .

2) You want your main thread to do something when all the threads finish .

You can create two CountDownLatch objects.

CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(N);

Then you can construct all the threads like this

Thread thread = new Thread(){
public void run(){
try{
startLatch.await();
// do the task
endLatch.countDown();
}catch(InterruptedException e){
Thread.currentThread.interrupt();
}

}
}


thread.start();

so when the thread starts it will block cause of the CountDownLatch (await method call)

when startLatch.countDown() is called the latch opens and all the threads can flow now and start working .

similarly the main thread that is waiting for all threads to finish .

will continue when all the threads have called endLatch.countDown()

No comments: