Java Concurrency Interview

Synchronizers: latches, barriers, semaphores question 46 of 180 mid

When would you use a latch as a starting gate rather than as a finish line?

The two-latch idiom is the standard way to create real contention, in tests and in benchmarks:

CountDownLatch start = new CountDownLatch(1);      // the gate
CountDownLatch done  = new CountDownLatch(threads); // the finish line

for (int i = 0; i < threads; i++) {
    new Thread(() -> {
        start.await();          // everyone piles up here (try/catch omitted)
        work();
        done.countDown();
    }).start();
}
start.countDown();              // released together
done.await(10, SECONDS);        // bounded, so a hang fails instead of hanging

Without the gate, thread 1 usually finishes before thread 8 has started, because starting a thread costs more than a short task body. A CyclicBarrier would also work for the gate, but it makes the workers wait for each other rather than for you, and it cannot express "one controller releases N workers".

synchronizers latch testing

Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction