What is the use of volatile modifier in Java?

 The volatile modifier is used only for the variable. When multiple threads use the value of a variable then there is a chance of data inconsistency, to overcome this problem we use the volatile modifier for that variable.  Once a variable declared as volatile, a separate copy of the variable is created for each thread and finally, the data inconsistency problem will overcome.

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.

The Java volatile keyword is used to mark a Java variable as "being stored in main memory". More precisely that means, that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache.

Example:

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