Can any one tell me the difference between volatile and static in java
I'm little confusion differen开发者_运维百科ce between volatile and static in java, Can any one explain me.
static
for a variable means it is class scoped, not instance scoped. I.e. there is only one of it, shared by every instance of the class. When you refer to a static
variable from outside its class, you need to qualify it with the class name, rather than with an instance of the class:
class Example {
static int staticVar = 0;
int instanceVar = 0;
}
Example ex = new Example();
ex.instanceVar = 1;
ex.staticVar = 2; // you may get an IDE/compiler warning for this
Example.staticVar = 3; // this is the best way to access your static variable
Th static
qualifier can also be used with methods (where it means the same), and for inner classes (where it means that inner class instances are not bound to any instance of the outer class).
volatile
is related to concurrent programming; it ensures that a variable can be shared between multiple threads (with some limitations).
So the two have not much in common except that both can qualify variables.
The volatile
and static
keywords have completely different meanings.
static
means the field (I'm assuming you're talking about fields, since methods can't be volatile
) does not belong to an individual objects, but to the class in which it is defined, and there is only one of it, rather than a different one for each instance of the class.
volatile
is only relevant if you have multiple threads accessing a field. In that case, it prevents the content of the field from being cached by individual threads. If a non-volatile
field is set in one thread and read in another, and this does not happen in a synchronized
block or method, the second thread could see the "old" value of the field for an arbitrarily long time.
In terms of variables, static
means there's one copy of the variable shared among all objects of the class rather than one per object.
In terms of functions, static
means that the function does not need an object in order for someone to call it: main
is the classic example of this.
On the other hand, volatile
means that variables can be changed external to the normal flow of control, meaning that accesses to it shouldn't be optimised.
The main difference is around threads and objects: basically a static variable 'belongs' to the class as apposed to the object instance whereas volatile refers to an instance variable and is used to protect it in a threaded environment in a similar way to synchronized.
More on volatile here: The volatile keyword in Java
精彩评论