您的位置:首页 > 其它

Double-checked locking and the Singleton pattern--双重检查加锁失效原因剖析

2015-08-24 10:52 435 查看
以下内容摘取自http://stackoverflow.com/questions/11195389/out-of-order-writes-for-double-checked-locking

Thread1 could  publish the [code]instance
reference to the main memory, but fail to publish any other data inside the
Singleton
object that wascreated. Thread2 will observe the object in an inconsistent state.

大概意思是Thread2有可能在Thread1构造函数执行一部分的时候读取Instance,比如Vector赋值,但inUser为false时,这时候就会造成两个线程获取的instance状态不一致。

[/code]

import java.util.Vector;

class Singleton {

private static Singleton instance;
private Vector v;
private boolean inUse;

private Singleton() {
v = new Vector();
v.addElement(new Object());
inUse = true;
}

public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) { // 1
if (instance == null) // 2
instance = new Singleton(); // 3
}
}
return instance;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: