双重检查锁定会尝试以线程安全的方式按需初始化字段,同时避免同步的开销。
遗憾的是,在未声明 volatile
的字段上使用时,它不具备线程安全性。
在使用 Java 1.4 或更低版本时,即便是 volatile
字段,双重检查锁定不起作用。
有关此问题的说明,请参阅本文。
示例:
class Foo {
private Helper helper = null
Helper getHelper() {
if (helper == null)
synchronized(this) {
if (helper == null) {
helper = new Helper()
}
}
}
return helper;
}
}