Wednesday 25 May 2016

Volatile vs Static


Many of us get confused with volatile and static varibale. Both of them maintain a single copy then why do we need a volatile variable static can do the thing.. But we cannot just compare static and volatile variable based on  the copies they store. The difference here is all about how they store (process they follow while storing).

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.

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.

This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value.
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.


Example:

Static Variable:  If two Threads(suppose T1 and T2) are accessing the same object and updating a variable which is declared as static then it means T1 and T1 can make their own local copy of the same object(including static variables) in their respective cache, so update made by T1 to the static variable in its local cache wont reflect in the static variable for T1 cache .


Volatile variable: If two Threads(suppose T1 and T2) are accessing the same object and updating a variable which is declared as volatile then it means T1 and T2 can make their own local cache of the Object except the variable which is declared as a volatile . So the volatile variable will have only one main copy which will be updated by different threads and update made by one thread to the volatile variable will immediately reflect to the other Thread.


Here is a diagram for better explanation:







No comments:

Post a Comment