Using volatile is a method (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class example can be used by multiple threads at the very time without any difficulty.
Examine a simple example.
class SharedObj
{
// Changes made to sharedVar in one thread
// may not immediately reflect in other thread
static int sharedVar = 6;
}
Assume that two threads are running on SharedObj. If two threads run on various processors each thread may have its local copy of the shared variable. If one thread changes its value the change might not reflect in the primary one in the main memory immediately. This depends on the reproduced policy of the cache. Now the other thread is not aware of the revised value which leads to data variance.
Note that write of standard variables without any synchronization actions, might not be noticeable to any reading thread (this behavior is called sequential consistency). Although most modern hardware stores good cache coherence, therefore, most probably the differences in one cache are reflected in other but it’s not a good method to rely on hardware to ‘fix’ a faulty application.
class SharedObj
{
// volatile keyword here makes sure that
// the changes made in one thread are
// instantly reflect in other thread
static volatile int sharedVar = 6;
}
Note that volatile should not be confounded with the static modifier. static variables are class members that are distributed among all objects. There is only one copy of them in the main memory