volatile keyword in java with example?

Volatile Keyword in java

Volatile is a keyword in java that is used to change the value during multiple threads’ access to it.

It applied to member variables only.

We have another keyword transient for variable declaration in java.

What happens if we declare a transient member variable in an object during a multi-thread application?

In multithreaded applications, the state of any object can be modified asynchronously by multiple threads.

It causes 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. In the case of the volatile keyword

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.

Step by step guide how volatile keywords in Multithreaded


It uses to have thread-safe objects.


private volatile String mState;

volatile keyword advantages

  • 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 the main memory and not from the thread-local cache in multi-threaded applications.
  • The volatile keyword is used for a variable when multiple threads try to access the variable.
  • This makes variable guarantees that always value is consistent.

Difference between volatile and static keyword in java

volatile and static are used to apply this to variables.

Each object has separate volatile variable valuestatic variable values always have a single value for multiple objects
volatile values are not cached and use the shared data among threadsThese values are cached per thread base, You will get inconsistent values for multiple thread access to it

Difference between volatile and synchronized keyword in java

volatile is a keyword used for variables and synchronized is a keyword applied to code blocks and methods. It is used to achieve data consistency during multi-thread applications

Applies to variablesapplies to methods and code blocks
Performance is goodDecreases performances in multiple threads access
There is no blocking a threadBlocking a thread for waiting