不好意思,问题没说完还,继续说对下面代码
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 = inst; //5
}
}
}
return instance;
}
中的第二把锁是不是有必要的问题,个人认为可以将上面代码改成如下:
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
Singleton inst = instance; //2
if (inst == null)
{
inst = new Singleton(); //3
instance = inst; //4
}
}
}
return instance;
}
我分析了一下,修改后的代码一样能实现解决"solve the out-of-order write problem" 的目的,同时跟修改前相比少一把锁的开销.
个人浅见,还望各位高手不吝指正,谢谢!