blog rss feed

Using CountDownLatch - Reducing thread contention article

Keywords:

Last editor: Dave Cherry, last modified: Oct 25, 2009

How do I use CountDownLatch?

Firstly, an instance of CountDownLatch is instantiated passing to the constructor the number of times that the latch must count down before going into the latched state. By latched state we mean the state in which await will no longer block.

?

So what can I use CountDownLatch for?

In our example we need to wait for a thread to initialise before proceeding. We achieve this by creating a count down latch with a count of 1. Once the thread has done its work, it calls countDown on the latch. In the mean time the main thread has continued to do its longJob and then called await on the CountDownLatch instance. Calling await blocks until countDown has been called enough times (in this case once).

Example source


// Example groovy source for a count down latch.
import java.util.concurrent.CountDownLatch


// create a latch that will wait for 1 countdown call.
CountDownLatch latch = new CountDownLatch(1);

// create and start the thread that we have to wait for.
new Thread({
    // simulate some tasks.
    Thread.sleep(100);

    println("Before latch is counted down")

    latch.countDown();
} as Runnable).start();

// perform the jobs on the main thread.
println("Before await");

// then await the latch
latch.await();

println("Returned from await");
<< 1 2 3 4

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30