报告双重检查锁定

双重检查锁定尝试以线程安全的方式按需初始化字段,同时避免同步的开销。 遗憾的是,在未被声明为 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;
      }
    }
    // 其他函数和成员…
  }