Volatile in Java

App Devops
1 min readMar 9, 2022

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe.

Case 1:

class MyObject
{
// Changes made to currentAction in one thread
// may not immediately reflect in other thread
static int currentAction = 5;
}

Just in case two threads working in MyObject. If two threads run on different processors each thread may have its own local copy of currentAction. If one thread modifies its value the change might not reflect in the original one in the main memory instantly. This depends on the write policy of cache. Now the other thread is not aware of the modified value which leads to data inconsistency.

Case 2:

class MyObject
{
// volatile keyword here makes sure that
// the changes made in one thread are
// immediately reflect in other thread
static volatile int currentAction = 5;
}

Note that volatile should not be confused with the static modifier. static variables are class members that are shared among all objects. There is only one copy of them in the main memory. The value of a volatile variable will never be stored in the cache. All read and write will be done from and to the main memory.

--

--