public class DoubleCheckVolatile {
private volatile static DoubleCheckVolatile doubleCheckVolatile;
public static DoubleCheckVolatile getDoubleCheckVolatile() {
if (doubleCheckVolatile != null)
return doubleCheckVolatile;
synchronized (DoubleCheckVolatile.class) {
if (doubleCheckVolatile != null)
return doubleCheckVolatile;
synchronized (DoubleCheckVolatile.class) {
doubleCheckVolatile = new DoubleCheckVolatile();
return doubleCheckVolatile;
}
}
}
private DoubleCheckVolatile() {
}
}
public class DoubleCheckAtomic {
private static AtomicReference<DoubleCheckAtomic> doubleCheckAtomicAtomicRef = new AtomicReference<>();
public static DoubleCheckAtomic getDoubleCheckAtomic() {
if (doubleCheckAtomicAtomicRef.get() != null)
return doubleCheckAtomicAtomicRef.get();
synchronized (DoubleCheckAtomic.class) {
if (doubleCheckAtomicAtomicRef.get() != null)
return doubleCheckAtomicAtomicRef.get();
synchronized (DoubleCheckAtomic.class) {
doubleCheckAtomicAtomicRef.set(new DoubleCheckAtomic());
return doubleCheckAtomicAtomicRef.get();
}
}
}
private DoubleCheckAtomic() {
}
}
这两个类的做法是否能都能防止对象初始化步骤被指令重排后导致的并发危险?