Voaltile Keyword in java explained by example

By | April 20, 2014

What is Volatile variable in java and how/where to use it ?
This is a famous interview question .You can expect this question in 7 out of 10 interviews, specially if you are from java background.While most of the programmers are aware of the definition . But they don’t know actually what it is?
In this article we will explain the use of volatile keyword by a simple example.As we always do we have tried to keep things as simple as possible.

What is volatile keyword ?
Consider the next few lines as golden words if you remember these you will be able to answer this question.

Each thread has its own stack, and so its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables in its own memory.And it manipulates variables from there itself. The volatile keyword is used to say to the jvm “Warning, this variable may be modified by some other Thread”. Without this keyword the JVM is free to make some optimizations, like never refreshing those local copies in some threads. The volatile force the thread to update the original variable for each variable. The volatile keyword could be used on every kind of variable, either primitive or objects.

Let’s see an example :
As I said Volatile keyword informs compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. consider this code

}

Here it’s not guaranteed that if one thread updates value of exit the other thread will see it .A thread is free to cache the value of exist and read it from there without reading it from main memory.So in that case the code may go into infinite loop.

Sometimes as soon as you finish with above answer you will be bombarded with this question
What are the places where the use of volatile keyword is appropriate ? or when to use volatile keyword ?

Form the above example it’s clear that wherever a variable is getting modified by more than one thread we can use volatile.Apart from that volatile keyword can be used to read and write long and double variables atomically, fixing double checked locking in Singleton pattern , as an alternate way of achieving synchronization etc.

Help us increase our audience by sharing this post or linking us on any of the social networks.

Leave a Reply

Your email address will not be published. Required fields are marked *