manbaum
2003-03-24 17:12

dcl = Double-checked locking

如下:

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 = new Singleton();
}
//instance = inst; //5
}
}
}
return instance;
}

我觉得没必要 dcl,两次 synchronized 难道不花费更多的时间么?本来为了提高性能,反而把问题复杂化了。

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 synchronized Singleton getInstance()
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}
}

这样不会影响多少性能,不就是等待一个 return 的时间么。

class Singleton
{
private Vector v;
private boolean inUse;
private static Singleton instance = new Singleton();

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

public static Singleton getInstance()
{
return instance;
}
}

也可以,不用等,只是没有了 lazy initialize 好处。

shyguy
2003-04-11 13:49

因为有的时候必须lazy-load!

whyenglish
2009-07-01 13:49

可以这样吗?
class Singleton
{
private static Singleton instance = null;
//enforce singleton
private Singleton() {
//...
}
public static Singleton getInstance()
{
if(instance == null){
synchronized(Singleton.class){
//check again
if(instance ==null ){
instance = new Singleton();
}
}
}
return instance;
}
}

不知道这样对性能的影响会有多大?一旦instance实例化后,第二次getInstance()就不会再运行到 synchronized(..)。为什么非要在方法上进行整个同步呢?这样做会产生多个Singleton的实例吗?
[该贴被whyenglish于2009-07-01 13:51修改过]