此代码用于演示双重检查锁定反模式:
@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;
}
}
我可以通过修改它来避免这个问题:
@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;
}
}
据我所知,
Resource r=new Resource();
resource = r;
该编译器应该为此提供发生之前的关系。