I'm trying to understand Java's volatile
keyword with respect to writing to a volatile atomic variable in a multithreaded program with CPU caches.
I've read several tutorials and the Java Language Specification, particularly section 17.4.5 on "happens-before ordering". My understanding is that when a thread writes a new value to a volatile variable, the updated value must be visible to other threads reading that variable. To me, these semantics can be implemented in one of two ways:
Threads can cache a volatile variable in the CPU cache, but a write to the variable in the cache must be flushed immediately to main memory. In other words, the cache is write-through.
Threads can never cache a volatile variable and must read and write such variables in main memory.
Approach 1 is mentioned in this tutorial (http://tutorials.jenkov.com) that says:
By declaring the counter variable volatile all writes to the counter variable will be written back to main memory immediately.
Approach 2 is mentioned in a Stackoverflow question "Volatile variable in Java" and also this tutorial that says:
The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"
Which one is the correct approach used in Java?
Related Stackoverflow questions which do not answer my question:
Does Java volatile read flush writes, and does volatile write update reads