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
Objectscreated 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
Objectfields, 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
staticor 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).
An additional interesting question would be: Is there a difference between a
staticvariable is stored once per class. A
static volatilevariable is stored once per class and will be accessed frequently by multiple threads, i.e. reads cannot be cached.