简体   繁体   English

为什么即使在波动的修复之后,双重检查锁仍然不鼓励?

[英]why is double checked locking still discouraged even after the volatile fix?

Reference article on JMM 关于JMM的参考文章

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. ) (但是,volatile的新语义允许使用双重检查锁定的常用方法之一才能正常工作, 尽管仍然不鼓励这种技术。

Related discussions: 相关讨论:

I can understand why it is broken without the volatile fix. 我能理解为什么没有volatile修复就会破坏它。 but I don't know why it is still discouraged even after the fix. 但我不知道为什么即使在修复之后它仍然气馁。 I noticed some disagreement in one of the discussions. 我注意到其中一个讨论中存在一些分歧。 but if it is really as the reference suggested ? 但如果它真的像参考建议的那样? what could be the reason this fixed version is still discouraged? 这个固定版本仍然不鼓励的原因是什么?

So first of all: with the new Java MM the double-checked locking idiom is not broken anymore. 所以首先:使用新的Java MM,双重检查的锁定习惯不再被打破。 So you can safely use it in Java. 所以你可以安全地在Java中使用它。

There are also situations where all other alternatives cannot be used (like enums or static initialization). 在某些情况下,无法使用所有其他替代方案(如枚举或静态初始化)。 For example, if you need access to a non-static reference in order to construct the singleton. 例如,如果您需要访问非静态引用以构造单例。

So it is safe to use as long as you have completely understood the idiom. 因此,只要您完全理解成语,它就是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM