通过双重检查锁(double-checked locking)(在并发场景下)实现延迟初始化的优化 问题隐患(可参考 The "Double-Checked Locking is Broken" Declaration),推荐解决方案中较为 简单一种(适用于 JDK5 及以上版本),将目标属性声明为 volatile 型(比如修改 helper 的属 性声明为`private volatile Helper helper = null;`)。
正例:
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null){
synchronized(Singleton.class){
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
反例:
public class
LazyInitDemo
{
private
Helper helper
=
null
;
public
Helper
getHelper
() {
if
(
helper
==
null
) {
synchronized
(
this
) {
if
(
helper
==
null
) {
helper
=
new
Helper
(); }
}
}
return
helper
;
}
// other methods and fields...
}