It is worth noting that broken techniques like double-checked locking are still broken under the new memory model, and that "fixing" double-checked locking was not one of the goals of the new memory model effort. (However, the new semantics of volatile allow one of the commonly proposed alternatives to double-checked locking to work correctly, although the technique is still discouraged.)
相关讨论:
- Why Double checked locking is 25% faster in Joshua Bloch Effective Java Example
- Why is double-checked locking broken in Java?
我能理解为什么它在没有 volatile
修复的情况下被破坏。但我不知道为什么即使在修复之后仍然不鼓励它。我注意到其中一次讨论中存在一些分歧。但如果它真的如引用所建议的那样?仍然不鼓励使用此固定版本的原因是什么?
最佳答案
所以首先:在新的 Java MM 中,双重检查锁定惯用语不再不再被破坏。所以你可以安全地在 Java 中使用它。
还有一些情况无法使用所有其他替代方案(如枚举或静态初始化)。例如,如果您需要访问非静态引用以构建单例。
所以只要完全理解成语就可以放心使用。
关于java - 为什么即使在 volatile 修复之后仍然不鼓励双重检查锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001653/