Main Memory
• The heap + static area of JVM.
• Stores all variables (shared across threads).
• Every read/write in theory should go here.
Thread Local Cache (Working Memory)
• Each thread keeps a local copy of variables it is using (in CPU registers or caches).
• Improves performance (avoids reading main memory repeatedly).
• But → can cause visibility issues: one thread’s update may not be visible to others
immediately.
Example
class Example {
boolean flag = false;
void writer() {
flag = true; // write may stay in thread’s cache
void reader() {
if (flag) { // may still see old value (false) from cache
System.out.println("Flag is true");
Without proper synchronization/volatile, reader() might never see flag = true.
Fix with volatile
volatile boolean flag = false;
• Ensures writes flush to main memory and reads fetch latest value.