Monday, December 19, 2011

what is volatile keyword in java?

Volatile Keyword Basics

Volatile is a keyword in java which is applicable to member variables only.
what does it mean if we declare a transient member variable in an object?
In the multithreaded applications, state of any object can be modified asynchronously by multiple threads
This causes the consistency to the state among different concurrent threads.
To maintain the consistency between all the threads for that state of an object we can declare a member variable as transient.
Whenever a thread is going to execute the object, it tries to get the state of an object from memory and save the state after thread execution is over, so that object's state can be consistent among concurrent multiple threads.


private volatile String mState;


volatile keyword is only used for variables. This keyword is not legal to use for class and methods.
The volatile variable value will be read from main memory and not from thread local cache in multi-threaded applications.
The volatile keyword is used for a variable when multiple threads trying to access the variable

Related article