先看一下double check的代码:
public class DclpSingleton {
private static volatile DclpSingleton instance = null;
private DclpSingleton() {}
public static DclpSingleton getInstance() {
if (instance == null) {
synchronized (DclpSingleton.class) {
if (instance == null) {
instance = new DclpSingleton();
}
}
}
return instance;
}
}
现在来思考以下问题:
- 不上锁也不进行二次判断会怎么样?
- 上锁不进行二次判断会怎么样?
- 上锁也进行二次判断,但instance不加volatile修饰会怎么样?
不加volatile会怎么样?
使用instance的内部成员时,有可能会出现空指针异常