先看一下double check的代码:

  1. public class DclpSingleton {
  2. private static volatile DclpSingleton instance = null;
  3. private DclpSingleton() {}
  4. public static DclpSingleton getInstance() {
  5. if (instance == null) {
  6. synchronized (DclpSingleton.class) {
  7. if (instance == null) {
  8. instance = new DclpSingleton();
  9. }
  10. }
  11. }
  12. return instance;
  13. }
  14. }

现在来思考以下问题:

  • 不上锁也不进行二次判断会怎么样?
  • 上锁不进行二次判断会怎么样?
  • 上锁也进行二次判断,但instance不加volatile修饰会怎么样?

不加volatile会怎么样?

使用instance的内部成员时,有可能会出现空指针异常