在程序开发中,有时需要推迟一些高开销的对象初始化操作,并且只有在使用这些对象时才进行初始化,此时开发者可能会采用延迟初始化。但要正确实现线程安全的延迟初始化需要一些技巧,否则容易出现问题,如下面例子所示。 **例1**:下面代码示例中:延迟初始化对象不是线程安全的。
public class UnsafeLazyInitialization {
private static Instance instance;
public static Instance getInstance() {
if (instance == null) { //1:Thread A executed
instance = new Instance(); //2:Thread B executed
}
return instance;
}
}
在例1中,假设A线程执行代码1的同时,B线程执行代码2。此时,线程A可能会看到instance引用的对象还没有完成初始化。 对应的解决方式,可以对getInstance()做同步处理来实现线程安全的延迟初始化。示例代码如下: **例2**:对getInstance()同步处理来实现线程安全的延迟初始化。
public class SafeLazyInitialization {
private static Instance instance;
public synchronized static Instance getInstance() {
if (instance == null) {
instance = new Instance();
}
return instance;
}
}
在例2代码示例中:如果getInstance()被多个线程频繁的调用,将会导致程序执行性能的下降。对此,开发人员想通过双重检查锁定来降低同步的开销。示例代码如下: **例3**:下面代码示例中:使用双重校验锁来实现延迟初始化。
public class DoubleCheckedLocking { //1
private static Instance instance; //2
public static Instance getInstance() { //3
if (instance == null) { //4:first check
synchronized (DoubleCheckedLocking.class) { //5:lock
if (instance == null) //6:second check
instance = new Instance(); //7:problem
} //8
} //9
return instance; //10
} //11
}
在例3的代码示例中:开发者试图通过检测第一次instance不为null,就不需要执行下面的加锁和初始化操作。希望可以大幅降低例2同步方法带来的性能开销。然而,这是一个错误的优化。在线程执行到第4行代码读取到instance不为null时,instance引用的对象有可能还没有完成初始化。原因如下: 第7行`instance = new Singleton();创建一个对象。这一行代码可以分解为如下的三行伪代码:`
memory = allocate(); //1:分配对象的内存空间
ctorInstance(memory); //2:初始化对象
instance = memory; //3:设置instance指向刚分配的内存地址
上面三行伪代码中的2和3之间,可能会被重排序。2和3之间重排序之后的执行时序如下:
memory = allocate(); //1:分配对象的内存空间
instance = memory; //3:设置instance指向刚分配的内存地址.注意,此时对象还没有被初始化
ctorInstance(memory); //2:初始化对象
根据Java语言规范《The Java Language Specification, Java SE 7 Edition》,所有线程在执行java程序时必须要遵守intra-thread semantics。intra-thread semantics保证重排序不会改变单线程内的程序执行结果。 但是当多线程执行时,线程可能会看到一个还没有被初始化的对象。 修复建议: 如果需要对实例字段使用线程安全的延迟初始化,请使用基于volatile的延迟初始化的方案。如果需要对静态字段使用线程安全的延迟初始化,基于类初始化的方案。两种方式示例如下。 **例1**:基于volatile的双重检查锁定的解决方案。
public class SafeDoubleCheckedLocking {
private volatile static Instance instance;
public static Instance getInstance() {
if (instance == null) {
synchronized (SafeDoubleCheckedLocking.class) {
if (instance == null)
instance = new Instance();//volatile instance
}
}
return instance;
}
}
这个解决方案需要JDK5或更高版本,因为从JDK5开始使用新的JSR-133内存模型规范,这个规范增强了volatile的语义。 **例2**:基于类初始化的解决方案。
public class InstanceFactory {
private static class InstanceHolder {
public static Instance instance = new Instance();
}
public static Instance getInstance() {
return InstanceHolder.instance ; //InstanceHolder class is initialized
}
}
JVM在类的初始化阶段(即在Class被加载后,且被线程使用之前),会执行类的初始化。在执行类的初始化期间,JVM会去获取一个锁。这个锁可以同步多个线程对同一个类的初始化。
如有问题,欢迎指正。