DCL双重检查锁为什么需要两层判断?

我们知道DCL双重锁的写法是:

if (null == singletonLazy) {
    synchronized (SingletonLazy5.class) {
        if(null == singletonLazy) {
            singletonLazy = new SingletonLazy5();
        }
    }
}

那么为什么有两层判断呢?写成下面这样有哪些缺点呢?

synchronized (SingletonLazy5.class) {
    if(null == singletonLazy) {
        singletonLazy = new SingletonLazy5();
    }
}
阅读 4.5k
1 个回答

因为一旦singletonLazy被正确初始化以后,每次访问null == singletonLazy一定能够得到false从而不会重新初始化。但是我们无需每次都通过上锁来判断null == singletonLazy。所以双重锁的目的是为了成功初始化singletonLazy之后不再触发加锁操作。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题