为什么singleton双重检查成例对Java 语言编译器不成立?
public class LazySingleton
{
private static LazySingleton m_instance = null;
private LazySingleton() { }
/**
* 静态工厂方法
*/
public static LazySingleton getInstance()
{
if (m_instance == null)
{
//More than one threads might be here!!!
synchronized(LazySingleton.class)
{
if (m_instance == null)
{
m_instance = new LazySingleton();
}
}
}
return m_instance;
}
}
java与模式中解释到:在Java 编译器中,LazySingleton 类的初始化与m_instance 变量赋值的顺序不可预料。如果一个线程在没有同步化的条件下读取m_instance 引用,并调用这个对象的方法的话,可能会发现对象的初始化过程尚未完成,从而造成崩溃。
第二句不理解!请指点!