Visibility and happens-before
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
explain why a thread may not see another's write.
Planned topics
- CPU caches and compiler reordering mean a write may not be visible to other threads.
- The Java Memory Model defines happens-before: if A happens-before B, B sees A's writes.
- Practical edges: unlock then lock of the same monitor; write then read of a
volatile;Thread.start()andjoin(); executor submit then task run, and task completion thenFuture.get(). - Without such an edge, a loop on a plain flag may never stop.
- Visibility and atomicity are different problems.
Draft outline details
Demonstration
boolean running = true; // not volatile
while (running) { work(); } // may spin foreverCheck your understanding
Name two actions that create a happens-before edge.
Show answer
Monitor unlock/lock, volatile write/read, start/join.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.