Can I declare something like this??
static volatile boolean first=false;
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With