Java Volatile Keyword

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 :

Threads may hold copies of variables from main memory in CPU caches.

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 :

The CPU cache used by Thread 1 and main memory contains different values for the counter variable.

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 :


Leave a Reply

Your email address will not be published. Required fields are marked *