ProLesson 9.4Advanced3 min readUpdated 30 October 2026
volatile and visibility
Why one thread may never see another thread's change, what volatile guarantees, and what it does NOT do.
Race conditions are about two writers clashing. There's a second, sneakier problem: visibility. One thread changes a variable, and another thread never sees the change.
01Why a change can be invisible
For speed, each CPU core has its own caches, and the JIT compiler may keep a variable in a register or move code around. Without a rule that forces sharing, a thread can keep reading its own stale copy:
java
class Worker {
private boolean running = true; // not volatile
void stop() { running = false; } // called from another thread
void work() {
while (running) { // may loop forever: it might never see false
// do work
}
}
}This bug may not show up on your laptop and then hang on a production server. The Java Memory Model only guarantees visibility when you use the right tools.
Loading the rest of the lesson…