private static volatile Something instance = null;

public static Something getInstance() {
  if (instance == null) {
    synchronized (XXX.class) {
      if (instance == null)
        instance = new Something();
    }
  }
  return instance;
}

private Something(){}
加volatile后可以在jdk1.5之后正常工作,在jdk1.5之前还是有问题的

单例模式推荐使用饿汉式,启动时直接完成初始化

 

参考Dong Lee的系列博客:http://ifeve.com/jmm-faq-dcl/

 

 

 volatile在初始化代码块的用途:jdk一个示例

懒汉式单例要加volatile吗

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-05
  • 2022-01-18
  • 2022-02-22
猜你喜欢
  • 2022-12-23
  • 2022-03-12
  • 2021-08-23
  • 2022-12-23
  • 2022-02-21
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案