51,394
社区成员




public class lazySingleton {
private static volatile lazySingleton m_instance=null;
private lazySingleton() {
// TODO Auto-generated constructor stub
System.out.println("构造函数");
}
public static lazySingleton getInstance(){
if(m_instance==null){
synchronized (lazySingleton.class) {
if(m_instance==null){
m_instance=new lazySingleton(); //疑惑一
}
}
}
return m_instance;
}
public void print(){
System.out.println("print");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
lazySingleton.getInstance().print();
}
}
synchronized public static lazySingleton getInstance(){
if(m_instance==null){
m_instance=new lazySingleton();
}
return m_instance;
}
0206106F call 01F6B210 ; allocate space for
; Singleton, return result in eax
02061074 mov dword ptr [ebp],eax ; EBP is &singletons[i].reference
; store the unconstructed object here.
02061077 mov ecx,dword ptr [eax] ; dereference the handle to
; get the raw pointer
02061079 mov dword ptr [ecx],100h ; Next 4 lines are
0206107F mov dword ptr [ecx+4],200h ; Singleton's inlined constructor
02061086 mov dword ptr [ecx+8],400h
0206108D mov dword ptr [ecx+0Ch],0F84030h
0206106A mov eax,0F97E78h public static lazySingleton getInstance(){
if(m_instance==null){ // B线程检测到m_instance不为空
synchronized (lazySingleton.class) {
if(m_instance==null){
m_instance=new lazySingleton(); // A线程被指令重排了,刚好先赋值了;但还没执行完构造函数。
}
}
}
return m_instance; // 后面B线程执行时将引发:对象尚未初始化错误。
}