Reprinted from: http://blog.csdn.net/hqq2023623/article/details/51011434
volatile
A good way to understand the volatile nature:
Treat individual reads / writes to volatile variables as synchronizing those individual reads / writes using the same lock
The happens-before rule of locks guarantees memory visibility between the two threads that release and acquire the lock,
This means that a read of a volatile variable will always see the last value written to the volatile variable by any thread
The semantics of the lock determine that the execution of the critical section code is atomic
If there are multiple volatile operations or compound operations such as volatile++ , these operations are not atomic as a whole
From JSR-133 , the write - read of volatile variables enables communication between threads
From a memory semantics point of view:
1.volatile write-read and lock release-acquisition have the same memory effect
2. volatile write and lock release have the same memory semantics
3. A volatile read has the same memory semantics as a lock acquisition
Memory semantics for lock release and acquisition
When the thread releases the lock, JMM will refresh the shared variables in the thread's corresponding local memory to the main memory
When a thread acquires a lock, JMM invalidates the local memory corresponding to the thread.
Thus, the code in the critical section protected by the monitor must read the shared variable from the main memory
volatile write - read memory semantics
When writing a volatile variable, JMM will refresh the shared variable value in the thread's corresponding local memory to the main memory
When reading a volatile variable, JMM invalidates the thread's local memory, and the thread then reads the shared variable from main memory