欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【并发编程】单例模式:双重检查锁(DCL)方式中的volatile的运用

程序员文章站 2024-02-29 18:31:46
...
class Singleton{
  //  private static Singleton instance;
    private static volatile Singleton instance;
    private Singleton(){ }
    public static Singleton getInstance(){
        if (instance==null){
            //synchronized 同步代码块内的程序指令可以发生重排序
            synchronized (Singleton.class) {
                if (instance==null){
                    instance = new Singleton();
                    /*
                    * 在JVM字节码指令中,
                    * instance = new Singleton()要被分开为:
                              调用Singleton构造函数初始化实例对象
                              将对象引用地址赋值给instance
                    
                  * 当instance未被volatile修饰时:
                    * 假设此时有两个线程调用getInstance()
                      如果以上指令发生重排序,会导致instance被优先赋值
                    * 若在线程1未完成构造函数的调用时,
                         线程2得到cpu时间片进行第一次if判断时会直接拿到没用经过初始化的对象
                    
                  * 解决方案:给instance加上volatile修饰防止重排序
                    * 可以避免volatile写操作前的指令跑到其后面,及先new Singleton()后instance赋值
                    *  
                    * */
                }
            }
        }
        return instance;
    }
}
相关标签: Java