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
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.