I read over here that volatile doesn't entail mutual exclusion locking, then how volatile ensures happens-before relationship or how volatile ensures that other thread reads updated value?
Please note that I have read this and this but it doesn't answer my question which is specifically about volatile and these answers in these questions really doesn't explain the point I am curious about.
CodePudding user response:
Actually, on most multi-CPU architectures, it's kind of the other way around. Locking and unlocking a mutex ensures "happens-before" because a mutex treats unlock operations the same as writes to a volatile variable, and it treats lock operations the same as reads.
The real magic happens in hardware: Most modern processors have special memory barrier instructions that user-mode programs can use to ensure coherence between different CPU caches when it is important.
Forcing coherence is expensive. If the caches had to always be coherent, programs would run much more slowly. The purpose of the memory barrier instructions is to mark the parts of the program where coherence really matters, and outside of those code regions, the CPUs are free to cache data independently of each other.
Reading and writing any volatile variable causes your program to execute memory barrier instructions that force the hardware to obey the "happens before" requirements of the Java Language Spec. And, locking and unlocking any mutex also causes your program to execute the same or similar instructions.
CodePudding user response:
Volatile ensure happens-before relationship by two mechanisms:
- If a variable is marked as volatile, then JVM implementation has to ensure that its value is never cache in L1/L2/L3 caches of the processor. Value of a volatile variable must be immediately flushed to main memory. It is mentioned in JVM specification section 4.5.
- Updates to volatile variable happens using compare-and-swap atomic instruction.
