Synchronizers: latches, barriers, semaphores question 53 of 180 senior
Is CountDownLatch.await() a happens-before edge?
- No, latches only coordinate timing
- Correct: Yes: everything before a
countDown()happens-before anything after a returningawait() - Only if the shared state is volatile
- Only when the count reaches zero from a single thread
Every synchroniser in java.util.concurrent documents its memory effects, and this is the half people
forget. Actions in a thread before it calls countDown() happen-before actions following a successful
return from await() in another thread.
That is what makes the ordinary pattern correct: worker threads write their results into plain,
unsynchronised fields or array slots, count down, and the coordinator reads them all after await()
with no further synchronisation. No volatile is needed, because the latch provided the edge.
The same guarantee exists across the package: a put into a BlockingQueue happens-before the take
that removes it, submitting a task to an executor happens-before the task running, a task's completion
happens-before Future.get() returns, and CyclicBarrier and Phaser publish everything done before
the arrival to everything after the release.
Quiz yourself on Synchronizers: latches, barriers, semaphores Suggest a correction