Volatile Solves the Variable Visibility Problem
volatile meets the visibility requirement of a variable and inserts a StoreLoad barrier after the write operation. Variables modified by this keyword are not cached by the CPU and can only be read from or written to the memory.
The following code may cause thread 1 fails to interrupt. Each thread has its own working memory during running. Thread 1 copies the value of the stop variable to its working memory during running. If thread 2 changes the value of stop and starts to do another task before the value of stop is written to the memory, thread 1 will keep executing doSomething(); because it does not know that thread 2 changes the stop variable.
Thread 1
boolean stop = false;
while(!stop){
doSomething();
}
Thread 2
stop = true;
Use volatile to modify the stop variable to solve the problem. In addition, volatile does not solve atomic problems. For example, if two threads are used to perform count++ and volatile long count=0, the result is incorrect.