I am working on someone's code and came across the equivalent of this:
for (int i = 0; i < someVolatileMember; i++) {
// Removed for SO
}
Where someVolatileMember
is defined like this:
private volatile int someVolatileMember;
If some thread, A, is running the for loop and another thread, B, writes to someVolatileMember
then I assume the number of iterations to do would change while thread A is running the loop which is not great. I assume this would fix it:
final int someLocalVar = someVolatileMember;
for (int i = 0; i < someLocalVar; i++) {
// Removed for SO
}
My questions are:
someVolatileMember
For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.
Unlike synchronized methods or blocks, it does not make other threads wait while one thread is working on a critical section. Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables.
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. It changes how the runtime is allowed to cache the value.
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.
Your understanding is correct:
Per the Java Language Specification, the semantics of a volatile
field ensure consistency between values seen after updates done between different threads:
The Java programming language provides a second mechanism,
volatile
fields, that is more convenient than locking for some purposes.A field may be declared
volatile
, in which case the Java Memory Model ensures that all threads see a consistent value for the variable (§17.4).
Note that even without the volatile
modifier, the loop count is likely to change depending on many factors.
Once a final
variable is assigned, its value is never changed so the loop count will not change.
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