Search code examples
javavolatile

Java volatile loop


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:

  • Just to confirm that the number of iterations thread A does can be changed while the for loop is active if thread B modifies someVolatileMember
  • That the local non-volatile copy is sufficient to make sure that when thread A runs the loop thread B cannot change the number of iterations

Solution

  • Your understanding is correct:

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

    2. Once a final variable is assigned, its value is never changed so the loop count will not change.