Skip to content
Ameen Abozaid
Planned lessonMID-004-L02

Visibility and happens-before

  • Lesson 2 of 9
  • Mid-level
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() and join(); executor submit then task run, and task completion then Future.get().
  • Without such an edge, a loop on a plain flag may never stop.
  • Visibility and atomicity are different problems.
Draft outline details

Demonstration

java
boolean running = true;                  // not volatile
while (running) { work(); }              // may spin forever

Check 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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.