我在阅读 这篇文章,讲的是关于“双重检查锁定”的内容。除了文章的主题之外,我想知道为什么作者在文章的某个地方使用了下面的习惯用语:
清单7. 尝试解决乱序写问题
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;
}
我的问题是:同步一些使用相同锁的代码两次有什么原因吗?这样做有什么目的吗?非常感谢您提前的帮助。