中国开发网: 论坛: 程序员情感CBD: 贴子 651669
Miracle: 那么问题来了
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
if (instance == null) //2
instance = new Singleton(); //3
}
}
return instance;
}

可能会导致如下的问题:

mem = allocate(); //Allocate memory for Singleton object.
instance = mem; //Note that instance is now non-null, but
//has not been initialized.
ctorSingleton(instance); //Invoke constructor for Singleton passing
//instance.

那么如果这样,会不会有所不同呢:

public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
if (instance == null)
{ //2
Singleton localVar = new Singleton();
localVar.DoSomething();
instance = localVar; //3
}
}
}
return instance;
}

会不会由于乱序执行导致仍然有同样的问题呢?
夫习拳艺者,对已者十之七八,对人者,仅十之二三耳。拳艺之道,深无止境。得其浅者,一人敌,得其深者,何尝不万人敌耶!
我的Google Picasa相册
我的新BLOG

相关信息:


欢迎光临本社区,您还没有登录,不能发贴子。请在 这里登录