Access to volatile fields through local variables

concurrency, java, performance, volatile

Solution

You must assign volatile variables to local fields if you plan on doing any sort of multi-step logic (assuming of course, that the field is mutable).

for instance:

volatile String _field;

public int getFieldLength() {
  String tmp = _field;
  if(tmp != null) {
    return tmp.length();
  }
  return 0;
}

if you did not use a local copy of `_field`, then the value could change between the "if" test and the "length()" method call, potentially resulting in an NPE.

this is besides the obvious benefit of a speed improvement by not doing more than one volatile read.

Problem

This question is somewhat continuation and expansion of this one, as I think perfect question: How does assigning to a local variable help here? This question based on `Item 71` of `Effective Java`, where it is suggested to speed up performance by introducing local variable in purpose of `volatile` field access: ``` private volatile FieldType field; FieldType getField() { FieldType result = field; if (result == null) { // First check (no locking) synchronized(this) { result = field; if (result == null) // Second check (with locking) field = result = computeFieldValue(); } } return result; } ``` So, my question is more common: should we always access to `volatile` fields through assigning their values to local variables? (in order to archive best performance). I.e. some idiom: we have some `volatile` field, call it just `volatileField`; if we want to read its value in multi-thread method, we should: - create local variable with same type: `localVolatileVariable` - assign value of volatile field: `localVolatileVariable = volatileField` read value from this local copy, e.g.: ``` if (localVolatileVariable != null) { ... } ```

Original source

Related problems