双重检查锁尝试以线程安全的方式按需初始化字段,同时避免同步的开销。
遗憾的是,在未声明 volatile
的字段上使用时,它不具备线程安全。
在使用 Java 1.4 或更高版本时,双重检查锁即便对 volatile
字段也行不通。
阅读上面的链接文章,了解对该问题的详细说明。
不正确的双重检查锁示例:
class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null)
synchronized(this) {
if (helper == null) helper = new Helper();
}
return helper;
}
}
// 其他函数和成员...
}