volatile keyword is used with variable not with class or method it is useful in modfing the values in case of multiple thread access.Hence it make the class thread safe.It doesnt load value from any local cache instead it perform the read and write operation from the main memory.
static int var=5;
In the above example, assume that two threads are working on the same class. Both threads run on different processors where each thread has its local copy of var. If any thread modifies its value, the change will not reflect in the original one in the main memory. It leads to data inconsistency because the other thread is not aware of the modified value.
static volatile int var =5;
In the above example, static variables are class members that are shared among all objects. There is only one copy 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.
Difference between synchronization and volatile keyword
Volatile keyword is a field modifier whereas Synchronized keyword modifies code blocks and methods.
The thread cannot be blocked for waiting in case of volatile.Threads can be blocked for waiting in case of synchronized.
volatile improves thread performance Synchronized methods degrade the thread performance.