Reputation: 19320
I was recently reading volatile fields are thread-safe because
When we use volatile keyword with a variable, all the threads read its value directly from the memory and don’t cache it
So it got me to wonder, for non-volatile fields, where would the thread read its value from? I thought everything was stored in memory.
Upvotes: 0
Views: 868
Reputation: 1632
A core/thread on a processor can take a copy of a non volatile
variable and place it in it's own cache (not main memory). This cached value gets updated but the main memory version does not until the thread deems it time to flush the value back.
In the event another core/thread tries to access the value from main memory, it may unknowingly find an out of date value.
The volatile modifier means that the variable data is kept up to date in main memory every time it changes and hence is always ready for when another thread needs to access/edit it.
Upvotes: 0
Reputation: 2608
Every thread has a Cache of the Main Memory.
A field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable
For Example we have this static counter that is not Thread Safe
static int counter = 0;
If two threads reads and write this variable it will be like this
Main memory - > static int counter
T1-> Cache of the Main Memory. Reads/Writes directly from Cache
T2-> Cache of the Main Memory. Reads/Writes directly from Cache
So it will be inconsistent when reading and writing.
static volatile int counter = 0;
Main Memory - > static int counter;
T1 - > Read and Writes directly from the memory
T2 - > Read and Writes directly from the memory
I hope I give you a simple summary about this. Because you will need to check more about concurrency and Atomic Access for the concurrency of variables Check more in the Java Docs
Upvotes: 0
Reputation: 26094
The statement you quote is a misconception. I recommend the following article: https://software.rajivprab.com/2018/04/29/myths-programmers-believe-about-cpu-caches/
if volatile variables were truly written/read from main-memory every single time, they would be horrendously slow – main-memory references are 200x slower than L1 cache references. In reality, volatile-reads (in Java) can often be just as cheap as a L1 cache reference, putting to rest the notion that volatile forces reads/writes all the way to main memory. If you’ve been avoiding the use of volatiles because of performance concerns, you might have been a victim of the above misconceptions.
Upvotes: 3