Shekhar Gulati is a Java Consultant with over 5 years experience.He is currently working with Xebia India an Agile Software Development company.The postings on this site and on his blog are his own and do not necessarily represent opinion of his employer. His own blog is at http://whyjava.wordpress.com/ and you can follow him on twitter here. Shekhar has posted 25 posts at DZone. View Full User Profile

CountDownLatch Use-Cases

08.24.2010
| 13235 views |
  • submit to reddit

CountDownLatch is one of the classes that was added to the Java 5 concurrency package. It allows one or more threads to wait until a set of operations being performed in other threads are completed. In this article, I will talk about two use-cases where CountDownLatch can be used:

Use-case 1 :  Achieving Maximum Parallelism

Sometimes we have a use-case where we want to start a number of threads at the same time to achieve maximum parallelism. For example, we want to test a class which creates a single instance of some class.

public class ObjectFactory {

private volatile MyObject object;

public MyObject getInstance() {
if (object == null) {
synchronized (this) {
if (object == null) {
object = new MyObject();
}
}
}
return object;
}
}
Now we need to test that this class will only create a single instance of MyObject even when multiple threads access it parallely. To test this we will create a CountDownLatch and initialize it with 1. Then each thread will wait in its run method until the count down of the latch reaches zero. Because CountDownLatch is initialized with 1, a single thread call to countDown method will trigger all other threads to start at approximately the same time.
@Test
public void shouldCreateOnlySingleIntsanceOfAClassWhenTestedWithParallelThreads() throws Exception{
final ObjectFactory factory = new ObjectFactory();
final CountDownLatch startSignal = new CountDownLatch(1);
class MyThread extends Thread {
MyObject instance;
@Override
public void run() {
try {
startSignal.await();
instance = factory.getInstance();
} catch (InterruptedException e) {
// ignore
}
}
}
int threadCount = 1000;
MyThread[] threads = new MyThread[threadCount];
for (int i = 0;i< threadCount;i++) {
threads[i] = new MyThread();
threads[i].start();
}
startSignal.countDown();
for (MyThread myThread : threads) {
myThread.join();
}
MyObject instance = factory.getInstance();
for (MyThread myThread : threads) {
assertEquals(instance, myThread.instance);
}
}


Use-case 2  : Wait for several threads to complete

The second use-case arises when we want to wait for several threads to complete their work. In this scenario we will initialize the CountDownLatch with the number of threads we want to wait for and then each thread will call the countDown method on finishing its work. We will use the same example used in the first use-case where we used the method to make one thread wait for another thread to complete its work.

@Test
public void shouldCreateOnlySingleIntsanceOfAClassWhenTestedWithParallelThreads()
throws Exception {
int threadCount = 1000;
final ObjectFactory factory = new ObjectFactory();
final CountDownLatch startSignal = new CountDownLatch(1);
final CountDownLatch stopSignal = new CountDownLatch(threadCount);
class MyThread extends Thread {
MyObject instance;

@Override
public void run() {
try {
startSignal.await();
instance = factory.getInstance();
} catch (InterruptedException e) {
// ignore
} finally {
stopSignal.countDown();
}
}
}
MyThread[] threads = new MyThread[threadCount];
for (int i = 0; i < threadCount; i++) {
threads[i] = new MyThread();
threads[i].start();
}
startSignal.countDown();
stopSignal.await();
MyObject instance = factory.getInstance();
for (MyThread myThread : threads) {
assertEquals(instance, myThread.instance);
}
}
Published at DZone with permission of its author, Shekhar Gulati.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Andrew Thorburn replied on Wed, 2010/08/25 - 12:09am

Very handy class - I was using it when trying to replicate a deadlock issue (I knew *why* it happened, but replicating it in an application server was not simple). Just generated ~600 threads, lined them all up, ready to go, with a CDL, and presto! Deadlock trivially replicated. Well, not quite that trivially. As it turns out it could take a couple of runs before it deadlocked, so what I ended up doing was looping around and around until it happened. Made use of a second CDL so that I would A) Know all the threads had finished before moving on to the next loop, and B) not butcher my machine by adding more threads when it was already deadlocked. But yes, very handy class *when you need it*.

Shekhar Gulati replied on Thu, 2010/08/26 - 8:22am in response to: Andrew Thorburn

Yes that could be another use case. I will update the article with your comment. Thanks Shekhar

Baptiste Wicht replied on Wed, 2010/09/01 - 12:36am

Hi, thanks for this post. But for me the first case will be better solved with a barrier (CyclicBarrier) to make all the threads starting at the same time. Is there a reason to prefer CountDownLatch over CyclicBarrier ? For the second case, we can also use a barrier, but this doesn't make a big difference.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.