双重检查锁定模式:是否破损? [英] Double checked locking pattern: Broken or not?
本文介绍了双重检查锁定模式:是否破损?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么模式被认为是破碎的?它看起来不错吗?任何想法?
Why is the pattern considered broken? It looks fine to me? Any ideas?
public static Singleton getInst() {
if (instace == null) createInst();
return instace;
}
private static synchronized createInst() {
if (instace == null) {
instace = new Singleton();
}
}
推荐答案
看起来不错,但这种技术有许多微妙的问题,通常应该避免。例如,考虑以下事件序列:
It looks okay at first glance, but this technique has many subtle problems and should usually be avoided. For example, consider the following sequence of events:
- 线程A注意到值是
未初始化,因此它获取
锁定并开始初始化
值。 - 允许编译器生成的代码
将共享变量更新为
- 线程B注意到共享的
变量已经初始化了(或者
出现),并返回其值。
因为线程B认为值
已经被初始化,所以它不会
获取锁。如果B在
初始化之前使用
对象,那么程序可能会崩溃。
您可以通过使用volatile关键字来正确处理单例实例来避免这种情况。
You could avoid this by using the "volatile" keyword to handle your singleton instances correctly
这篇关于双重检查锁定模式:是否破损?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文