Friday, August 4, 2017

static vs volatile in java

 A very common interview question asked from mid level experience java developer and the question is: What is the difference between static and volatile variable in java?

So lets try to divide it in two parts:

 What is a Static variable in java:

Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However, threads may have locally cached values of it.


What is volatile in java:

When a variable is volatile and not static, there will be one variable for each Object. So, on the surface it seems there is no difference from a normal variable but totally different from static. However, even with Object fields, a thread may cache a variable value locally.


Static and volatile are introduced for special purposes in java. Volatile keyword mainly used in multi threading environment. How?

Declaring a variable as volatile (be it static or not) states that the variable will be accessed frequently by multiple threads. In Java, this boils down to instructing threads that they can not cache the variable's value, but will have to write back immediately after mutating so that other threads see the change. (Threads in Java are free to cache variables by default). 

 help my cause here 

An additional interesting question would be: Is there a difference between a static and a static volatile variable?

static variable is stored once per class. A static volatile variable is stored once per class and will be accessed frequently by multiple threads, i.e. reads cannot be cached.


Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.
However, volatile is not a substitute for proper synchronization!


These are the basic differences between static and volatile as I can think off.

Please do add a comment if you found some other difference, I will add them in this post.

Thanks for reading.

We have another website: HowToSaveMoney and OnePaisa.in

4 comments:

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...