This code is used to demonstrate double-checked-locking anti-pattern:
@NotThreadSafe
public class DoubleCheckedLocking {
private static Resource resource;
public static Resource getInstance() {
if (resource == null) {
synchronized (DoubleCheckedLocking.class) {
if (resource == null)
resource = new Resource();
}
}
return resource;
}
}
Can I just avoid this problem by modify it to:
@NotThreadSafe
public class DoubleCheckedLocking {
private static Resource resource;
public static Resource getInstance() {
if (resource == null) {
synchronized (DoubleCheckedLocking.class) {
if (resource == null){
Resource r=new Resource();
resource = r;
}
}
}
return resource;
}
}
As far as I know,
Resource r=new Resource();
resource = r;
That compiler should provide happen-before relationship for that.
As far as I know, the only known implementation of the double-checked locking pattern that works (for JDK5 and above) makes use of the ‘volatile’ keyword. See Fixing Double-Checked Locking using Volatile