Volatile decorated member variables are forced to reread the value of the member variable from shared memory each time it is accessed by the thread.
also, when a member variable changes, the thread is forced to write the change value back to the shared memory.
so at any given moment, two different threads always see the same value for a member variable.
The Java language Specification states that in order to achieve optimal speed, the thread is allowed to save private copies of shared member variables, and only when a thread enters or leaves a synchronized code block, it is compared to the original value of the shared member variable. This way, when multiple threads interact with an object at the same time, it is important to notice that the thread gets the change in the shared member variable in a timely manner.
The volatile keyword is the hint VM: You cannot save its private copy for this member variable, but you should interact directly with the shared member variable.
Recommendation: Use volatile on member variables accessed by two or more threads. You do not have to use when the variable you want to access is already in a synchronized code block, or it is a constant. Because using volatile masks the necessary code optimizations in the VM, it is less efficient, so use this keyword when necessary.