懒汉式单例要加volatile吗

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一个示例

 

posted @ 2018-08-23 13:56  funny_coding  阅读(633)  评论(0编辑  收藏  举报
build beautiful things, share happiness