volatile in the Java Memory Model: Formal Guarantees
You'll learn: How the Java Memory Model formally defines volatile behavior through memory barriers and ordering rules.
The Formal Definition
The Java Memory Model (JMM) provides precise guarantees for volatile variables that go beyond simple visibility. When you use volatile, the JMM enforces strict ordering rules through memory barriers (also called fences) that prevent instruction reordering by both the compiler and processor.
Store-Load Barriers
A volatile write triggers a store-store barrier before it and a store-load barrier after it:
volatile boolean flag;
int data;
// Thread 1
data = 42; // Normal write
flag = true; // volatile write (store-store barrier ensures data is visible)
// Thread 2
if (flag) { // volatile read (store-load barrier ensures fresh read)
System.out.println(data); // Guaranteed to see 42
}
Before the volatile write: All preceding writes (including non-volatile ones) must be flushed to main memory.
After a volatile read: All subsequent reads must fetch fresh values from main memory.
Preventing Instruction Reordering
The JMM forbids specific reorderings around volatile:
- Normal writes before a volatile write cannot move after it
- Normal reads after a volatile read cannot move before it
- Volatile accesses cannot be reordered with each other
This creates "safe publication" zones where side effects are guaranteed visible across threads.
The Happens-Before Edge
Formally, a volatile write happens-before every subsequent volatile read of that same variable. This transitive relationship extends to all operations before the write and after the read, creating a synchronization boundary.
Key Takeaway: The JMM guarantees that volatile uses memory barriers to prevent reordering and ensures all writes before a volatile write are visible to threads that perform a subsequent volatile read, creating a formal synchronization protocol lighter than full locks.