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

发布于 2022-09-06 23:06:38 字数 430 浏览 16 评论 0

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北渚 2022-09-13 23:06:38

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文