Java Memory Model
Java Memory Model
The Java Memory Model (JMM) defines how threads in a Java program interact through
memory, specifying rules for visibility, ordering, and atomicity of shared variables in a
multithreaded environment. It ensures consistent and predictable behavior of concurrent
Java programs, especially when multiple threads read and write shared data.
● CPU caches
● Compiler optimizations
● Instruction reordering
JMM specifies how and when changes made by one thread become visible to others,
preventing subtle bugs caused by race conditions or memory inconsistencies.
○ Every thread has its own working memory (a local copy of variables).
○ The main memory holds the “true” values of variables shared by all
threads.
○ Threads read variables from and write variables back to main memory, but
may keep local cached copies.
● One thread may update a variable, but others might still see the old value.
⚙️ Synchronization Mechanisms
● Synchronized blocks/methods:
Enforce mutual exclusion and memory visibility. When a thread exits a
synchronized block, changes are flushed to main memory; when entering,
variables are reloaded.
● Volatile variables:
Lightweight visibility guarantees without locking but no mutual exclusion.
CopyEdit
class SharedData {
}
Here, the flag variable’s volatile modifier ensures that changes made by one thread in
writer() are visible to other threads in reader().
🧠 Summary
● JMM defines rules for how threads interact via memory in Java.