My question applies to a field which is initially null
, then is initialised to a non-null
value, and then doesn’t change anymore.
As this field needs to be available as soon as possible to all threads, I need to use volatile
.
But if I want to avoid the overhead of volatile
access whenever possible (i.e. when a non-volatile
field is enough), would the following code make any sense?
public class User {
private String nonVolatileName;
private volatile String volatileName;
public String getName() {
final String name = nonVolatileName;
return name != null ? name : volatileName;
}
private void initName() {
volatileName = nonVolatileName = expensiveComputation();
}
…
}