Consider this code based on the examples on Wikipedia but note that the question isn't restricted to Java.
class Foo {
private Helper helper;
private int initialized = 0;
public Helper getHelper() {
if (initialized == 0) {
synchronized (this) {
if (helper == null) {
helper = new Helper();
}
}
initialized = 1;
}
return helper;
}
}
Using a separate flag which is set outside the synchronized block should fix the issue with classic double-checked locking. When initialized is set to 1, helper is guaranteed to be visible to other threads since exiting the synchronized block should provide a memory barrier. The helper == NULL check inside the synchronized block should make sure that helper isn't created twice.
Is this variant of double-checked locking safe?