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
volatilefield, call it justvolatileField;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) { ... }
- create local variable with same type: