Why a memory model exists
A multithreaded program shares memory, but the compiler, the runtime, and the hardware all reorder and cache operations for speed. The Java Memory Model (JMM) is the contract that says which values a read is allowed to return, so programs behave predictably across every platform.
The core relations
The JMM is built on a few formal relations rather than on intuition about timing.
- Program order is the order of actions within a single thread.
- Synchronizes with links a release action to a later acquire, such as unlocking then locking the same monitor, or writing then reading a volatile field.
- Happens before is the transitive closure of program order and synchronizes with. If A happens before B, B sees A.
Visibility guarantees
If two accesses to the same location are not ordered by happens before and at least one is a write, that is a data race, and the read may see a stale or surprising value. Correct synchronization, through volatile, locks, or final fields, creates the ordering that makes writes visible.
Key idea
The Java Memory Model uses happens before, built from program order and synchronizes with edges, to define exactly which writes a read may legally observe.