First we know that the memory model in Java
That is: Thread working memory--Main memory
Working memory is thread-private, and main memory is thread-shared
The initialization of the variable is generated in the main memory, and the working memory is loaded from the main memory only when the variable is used
Total of eight atomic operations, Read,load,use,assign,store,wirte,lock,unlock
The Java Virtual Machine specification does not allow a thread (which we call thread a) to discard its most recent assign operation, meaning that the variable (which we call X) needs to be synchronized to the main memory after it has been modified in working memory, but does not specify a synchronization time
Non-volatile variables are too easy to cause inconsistencies between threads, so don't give an example
So volatile must be able to achieve synchronization effect? Not necessarily, or most of the cases, cannot be
The JVM specification declares volatile variables with two attributes:
1. Immediate visibility after modification
2. Prohibition of command (assembly or level of machine instructions) rearrangement
The first article is about the read-write atomicity of the volatile variable, meaning that the volatile will be read&load before it is read and will store&wirte after writing.
So like X + + this operation, why not
Analysis:
X + + operations are actually
- temp = x;
- temp = temp + 1;
- x = temp;
Here 1,3 are atomic operations, but the whole of the three-to-one is not an atomic operation, that is, the thread A, B, is performing x + + operations, the following may occur:
A:temp = x;
B:temp = x;
A:temp = temp + 1;
a:x = temp;
B:temp = temp + 1;
b:x = temp;
Above, there is a problem!
The understanding of volatile in Java