Double checked locking Article(双重检查锁定文章)
问题描述
我正在阅读关于Double-已检查锁定"并且超出了本文的主要主题,我想知道为什么在文章的某些地方作者使用了下一个成语:
I was reading this article about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom:
清单 7. 尝试解决乱序写入问题
Listing 7. Attempting to solve the out-of-order write problem
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
Singleton inst = instance; //2
if (inst == null)
{
synchronized(Singleton.class) { //3
inst = new Singleton(); //4
}
instance = inst; //5
}
}
}
return instance;
}
我的问题是:有什么理由用同一个锁同步两次代码吗?这有什么目的吗?
And my question is: Is there any reason to synchronize twice some code with the same lock? Have this any purpose it?
非常感谢.
推荐答案
两次锁定的目的是尝试防止乱序写入.内存模型指定了可能发生重新排序的位置,部分是根据锁.锁确保在instance = inst;"之后不会出现任何写入(包括单例构造函数中的任何写入).行.
The point of locking twice was to attempt to prevent out-of-order writes. The memory model specifies where reorderings can occur, partly in terms of locks. The lock ensures that no writes (including any within the singleton constructor) appear to happen after the "instance = inst;" line.
但是,要深入了解该主题,我建议 Bill Pugh 的文章.然后永远不要尝试它:)
However, to go deeper into the subject I'd recommend Bill Pugh's article. And then never attempt it :)
这篇关于双重检查锁定文章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:双重检查锁定文章
基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01