The Java volatile keyword guarantees visibility of changes to variables across threads.
In a multithreaded applications, where the threads operate on non-volatile variables, each thread may copy variables from main memory into a CPU cache while working on them, for performance reasons. If computer contains more than one CPU, each thread may run on a different CPU. It means that each thread may copy variables into the CPU cache of different CPUs. Below is illustration :
If two or more threads read data from the same variable, then there is no guarantee that if one of the threads changes variable value it will be written from the CPU cache back to main memory. This means that variable value in CPU cache may not be the same as in main memory. See illustration :
This situation is called “visibility problem”. The updates of one thread are not visible to other threads. Using volatile keyword is one of possible solutions of this issue. See example below :