Search code examples
javamultithreadingmemoryvolatile

If volatile fields are read directly from memory, where are non-volatile fields read from?


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.


Solution

  • 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.