1. When using a multithreaded synchronization variable, the thread copies a member variable (such as B) in order to improve its efficiency, and the access to a in the thread actually accesses B. Synchronization of A and B occurs only in certain actions. Thus there is a and B inconsistency. Volatile is used to avoid this situation. volatile tells the JVM that the variable it modifies does not keep the copy and accesses the main memory directly (that is, a above)
2. In the Java memory model, there are main memories, and each thread has its own memory (for example, a register). For performance, a thread keeps a copy of the variable to be accessed in its own memory. This will cause the same variable to appear in a moment when the value in the memory of one thread may be inconsistent with the value in the memory of another thread, or the value in main memory.
A variable declared as volatile means that the variable is modified by other threads at any time, so it cannot be cache in the thread memory.
3.Volatile generally cannot replace sychronized, because volatile does not guarantee the atomicity of the operation, even if it is only i++, is actually composed of multiple atomic operations: Read I; Inc; Write I, if multiple threads execute i++,volatile at the same time can only guarantee that I is the same piece of memory, but it is still possible to write dirty data. If you add atomic wrapper classes with Java 5, you do not need sychronized for operations such as their increase.
The 4.volatile keyword is used to declare simple type variables such as int, float, and Boolean data types. If these simple data types are declared volatile, the operation on them becomes atomic level.
5. Be cautious when using the volatile keyword, not as long as the simple type variable uses the volatile modifier, all operations on the variable are atomic, and when the value of the variable is determined by its own previous decision, such as N=n+1, n++, and so on, the volatile keyword is invalidated, The action on a variable is atomic level only if its value is independent of its previous value, such as n = m + 1, which is the original level.
Source: http://sakyone.iteye.com/blog/668091
Key word volatile in Java