volatile is a lightweight synchronization mechanism provided by the Java virtual machine. There are three major characteristics:
First, to ensure the visibility of
1, code demonstrates
2, volatile is how to ensure the visibility of it?
If you declare a variable volatile write operation is performed, JVM will be sent to a processor Lock prefix instructions.
Data 1) where this variable cache line is written back to system memory.
2) The write-back cache memory handling can lead to invalid memory address data in other CPU inside.
Second, do not guarantee atomicity
1, code demonstrates
2, volatile why not ensure atomicity?
n ++ split into three instructions:
getfield get the original value from main memory
iadd are incremented thread working memory
putfield the value of the accumulated write-back to main memory
3, how to solve the problem of atomicity
the synchronized
Lock
AtomicInteger
Third, prohibit instruction reordering