zoukankan      html  css  js  c++  java
  • 懒汉式单例要加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一个示例

  • 相关阅读:
    Tye exception
    DataSeeder
    angular
    认证Authentication
    MVC
    Ef Core
    工作单元
    VirtualFileSystem
    中间件
    日志
  • 原文地址:https://www.cnblogs.com/yszzu/p/9523340.html
Copyright © 2011-2022 走看看