单例模式

单例模式第一版

public class Singleton {
 
      private Singleton(){};
   
       private static Singleton instance = null;
       public static Singleton getInstance(){
            if(instance == null){
                   instance = new Singleton();
            }
            return instance;
       }
        
}

懒汉模式:单例的初始值为null。

饿汉模式:一开始就给单例new了一个对象。

(饿汉主动找食物,懒汉等着别人喂)


单例模式第二版

public class Singleton {

       private Singleton(){};

       private static Singleton instance = null;

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

双重检测机制:

1.为了防止new Singleton被执行多次,因此在new操作之前加上Synchronized 同步锁,锁住整个类(注意,这里不能使用对象锁)

2.进入Synchronized 临界区以后,还要再做一次判空。因为当两个线程同时访问的时候,线程A构建完对象,线程B也已经通过了最初的判空验证,不做第二次判空的话,线程B还是会再次构建instance对象。
***异常情况***
单例模式第三版
public class Singleton {

       private Singleton(){};

       private volatile static Singleton instance = null;

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



volatile关键字:阻止变量访问前后的指令重排,保证了指令的执行顺序。
指令重排:

指令重排是什么意思呢?比如java中简单的一句 instance = new Singleton,会被编译器编译成如下JVM指令:


memory =allocate();    //1:分配对象的内存空间 

ctorInstance(memory);  //2:初始化对象 

instance =memory;     //3:设置instance指向刚分配的内存地址 


但是这些指令顺序并非一成不变,有可能会经过JVM和CPU的优化,指令重排成下面的顺序:


memory =allocate();    //1:分配对象的内存空间 

instance =memory;     //3:设置instance指向刚分配的内存地址 

ctorInstance(memory);  //2:初始化对象 


当线程A执行完1,3,时,instance对象还未完成初始化,但已经不再指向null。此时如果线程B抢占到CPU资源,执行  if(instance == null)的结果会是false,从而返回一个没有初始化完成的instance对象


--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
(来自程序员小灰)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值