在 Effecitve Java 一书的第 48 条中提到了双重检查模式,并指出这种模式在 Java 中通常并不适用。该模式的结构如下所示:
1. public Resource getResource() {
2. if (resource == null) {
3. synchronized(this){
4. if (resource==null) {
5. new Resource();
6. }
7. }
8. }
9. return resource;
10. }
该模式是对下面的代码改进:
1. public synchronized Resource getResource(){
2. if (resource == null){
3. new Resource();
4. }
5. return resource;
6. }
这段代码的目的是对 resource 延迟初始化。但是每次访问的时候都需要同步。为了减少同步的开销,于是有了双重检查模式。
在 Java 中双重检查模式无效的原因是在不同步的情况下引用类型不是线程安全的。对于除了 long 和 double 的基本类型,双重检查模式是适用 的。比如下面这段代码就是正确的:
1. private int count;
2. public int getCount(){
3. if (count == 0){
4. synchronized(this){
5. if (count == 0){
6. //一个耗时的计算
7. }
8. }
9. }
10. return count;
11. }
上面就是关于java中双重检查模式(double-check idiom)的一般结论。但是事情还没有结束,因为java的内存模式也在改进中。Doug Lea 在他的文章中写道:“根据最新的 JSR133 的 Java 内存模型,如果将引用类型声明为 volatile,双重检查模式就可以工作了
所以以后要在 Java 中使用双重检查模式,可以使用下面的代码:
1. private volatile Resource resource;
2. public Resource getResource(){
3. if (resource == null){
4. synchronized(this){
5. if (resource==null){
6. new Resource();
7. }
8. }
9. }
10. return resource;
11. }
当然了,得是在遵循 JSR133 规范的 Java 中。
所以,double-check 在 J2SE 1.4 或早期版本在多线程或者 JVM 调优时由于 out-of-order writes,是不可用的。 这个问题在 J2SE 5.0 中已经被修复,可以使用 volatile 关键字来保证多线程下的单例。
1. public class Singleton {
2. private volatile Singleton instance = null;
3. public Singleton getInstance() {
4. if (instance == null) {
5. synchronized(this) {
6. if (instance == null) {
7. new Singleton();
8. }
9. }
10. }
11. return instance;
12. }
13. }
推荐方法 是Initialization on Demand Holder(IODH),
1. public class Singleton {
2. static class SingletonHolder {
3. static Singleton instance = new Singleton();
4. }
5.
6. public static Singleton getInstance(){
7. return SingletonHolder.instance;
8. }
9. }