在现实世界的Java应用程序中使用Singleton模式和破坏的双重检查锁定 [英] Singleton pattern and broken double checked locking in a real-world Java application

查看:130
本文介绍了在现实世界的Java应用程序中使用Singleton模式和破坏的双重检查锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读文章 双重检查锁定和单例模式 ,关于双重检查锁定如何被破坏,以及Stack  Overflow上的一些相关问题。

I was reading the article Double-checked locking and the Singleton pattern, on how double checked locking is broken, and some related questions here on Stack Overflow.

我已多次使用此模式/习语而没有任何问题。由于我一直在使用Java 5,我首先想到的是,这已经在Java 5内存模型中得到了纠正。然而文章说:

I have used this pattern/idiom several times without any issues. Since I have been using Java 5, my first thought was that this has been rectified in Java 5 memory model. However the article says:


本文引用Java Memory
模型之前修改为Java
5.0 ;关于内存排序的陈述可能不再正确。 然而,
双重检查的锁定习惯用法在新内存模式
下仍然是

This article refers to the Java Memory Model before it was revised for Java 5.0; statements about memory ordering may no longer be correct. However, the double-checked locking idiom is still broken under the new memory model.

这是一个真正的问题,如果是这样,在什么条件下?

Is this a real problem, and, if so, under what conditions?

推荐答案

说明单身人士的例子关于双重检查的锁定看起来很聪明但是已经坏了



同步块的开始保证你能看到最新的数据,但它不保证重新排序,你除非
也在同步块中,否则不能指望一致的数据视图。它不能保证在同步部分内完成的变量修改对其他线程是可见的。只有进入同步块的线程才能保证看到更改。这就是为什么双重检查锁定被打破的原因 - 它在读者方面没有同步。 阅读主题可能会看到单例不为空,但单例数据可能无法完全初始化(可见)

另一方面按顺序,由volatile提供排序,保证排序,例如写入volatile 单例静态字段保证在写入易失性静态字段之前完成对单例对象的写入。它不会阻止创建两个对象的单例;这是由同步提供的。
类最终静态字段不需要是volatile。在Java中,JVM负责处理此问题。

On the other hand, ordering is provided by volatile which guarantees ordering, for instance write to volatile singleton static field guarantees that writes to the singleton object will be finished before the write to a volatile static field. It doesn't prevent creation singleton of two objects; this is provided by synchronize. Class final static fields doesn't need to be volatile. In Java, the JVM takes care of this problem.

更多信息可以在以下网址找到:

More can be found in:

  • Double-checked locking: Clever, but broken
  • The "Double-Checked Locking is Broken" Declaration

这篇关于在现实世界的Java应用程序中使用Singleton模式和破坏的双重检查锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆