问题:请看下面的代码,有个两个线程,线程A和线程B,时间上线程A先于线程B执行,线程A刚执行完synchronized代码块(语句7),在构造实例时是乱序执行的,如:第1步,在堆中分配空间;第2步,返回引用给instance变量;第3步,调用LazySingleton的构造函数进行初始化。在JDK1.5的内存模型下,线程A刚执行完synchronized代码块(语句7),线程B开始执行语句2,这时线程B得到的instance,会不会还未完成初始化完。如果不会的话,是volatile保证了构造实例过程的正确顺序,还是synchronized代码块中构造实例的过程压根就不能乱序执行?并请帮忙指出在Java Language Specification的出处。如果会的话,那就说下面的DCL解决方法在JDK1.5的内存模型下依然有问题。
[code="java"]
public class LazySingleton {
private int xxx;
private volatile static LazySingleton instance;
private LazySingleton() {
this.xxx = 100; // (1)
}
public static LazySingleton getInstance() {
if (instance == null) { // (2)
synchronized(LazySingleton.class) { // (3)
if (instance == null) { // (4)
instance = new LazySingleton(); // (5)
} // (6)
} // (7)
} // (8)
return instance; // (9)
}
public int getXxx() {
return xxx; // (10)
}
}
[/code]