Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can volatile variable be defined as static in java?

Can I declare something like this??

static volatile boolean first=false; 
like image 616
Saurabh Kumar Avatar asked Mar 27 '11 19:03

Saurabh Kumar


People also ask

Is volatile static Java?

static variables are shared among objects under a thread? This should read static variables are shared among objects all objects regardless of threads. "volatile variables are shared among multiple threads(so objects as well)." Volatile does not change how variables are shared among multiple threads or objects.

Can static be volatile?

Even if the static variables are shared variables, but in different thread there can be different values for a static variable in the local cache of a thread. To make it consistent for all threads, just declare it as static volatile .

How do you define a volatile variable in Java?

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.

Can a variable be static in Java?

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.


1 Answers

To expand on Michael's comment.

static simply means not associated with an instance of the containing class.

volatile simply means that the value may be changed by other threads without warning.

So your question boils down to "can a field not associated with an instance of the containing class be changed by another thread without warning?"

As Michael pointed out, the answer to that question is yes. Instance association is orthogonal to concurrent modification.

like image 137
Mike Samuel Avatar answered Oct 05 '22 22:10

Mike Samuel