0% found this document useful (0 votes)
16 views1 page

Main Memory Vs Thread Local Cache in Java (JMM)

Uploaded by

gopalv12345678
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views1 page

Main Memory Vs Thread Local Cache in Java (JMM)

Uploaded by

gopalv12345678
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

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.

You might also like