Is the following class thread safe? I am worrying about concurrent read and write the initialized variable. If it is not thread safe, how to make it thread safe?
- I know convert methodA to synchronized will help, but I don’t want to do this
- How about add volatile keywork to “initialized” variable?
public class A {
private boolean initialized;
public synchronized void init(String configFilePath) {
if (initialized) {
return;
}
initialized = true;
}
public void methodA() {
if (!initialized) {
throw new ConfigurationException()
}
}
}
Update1:
The initialized variable will only be modified once in init method, all other methods will only ready. If that is the case, adding volatile to initialized will make it thread safe, is that correct?
No, it is not thread safe. The
initroutine could be in the middle of settinginitializedwhenmethodAis called. SincemethodAis not synchronized, there’s nothing preventing a race between executinginitialized = trueand the read inif( !initialized). In fact, the write could even have happened but simply not yet propagated to the thread that calledmethodAAdding
volatiletoinitializedwould help with the value propagation problem, but not with the first.For more info on this, I recommend Brian Goetz’s article Managing Volatility.