[阅读: 359] 2008-07-04 07:41:45
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