Last editor: Dave Cherry, last modified: Oct 25, 2009
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.
?
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 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");