Java并发:线程安全的单例模式

转载请注明出处:jiq•钦'stechnical Blog

1、饿汉式

public class Singleton {
  private final static Singleton INSTANCE = new Singleton();
  private Singleton() { }
  public static Singleton getInstance() {
     return INSTANCE;
   }
} 
缺点:类加载时即分配空间,若不使用则较为占用内存空间。


2、懒汉式

2.1普通加锁模式

public class Singleton {
  private static Singleton instance = null;
  private Singleton() { }
 
  public static synchronized Singleton getInstance() {
     if(instance == null) {
        instance = new Singleton();
     }
     return instance;
   }
} 
缺点:每个线程调用getInstance都要加锁,效率低,我们想要只在第一次调用getInstance时加锁,请看下面的双重检测方案


2.2占位符模式(推荐)

属于懒汉式单例,因为Java机制规定,内部类SingletonHolder只有在getInstance()方法第一次调用的时候才会被加载(实现了lazy),而且其加载过程是线程安全的。内部类加载的时候实例化一次instance。

public class Singleton {
  private Singleton() { }
   privatestatic class SingletonHolder {  
//内部类,第一次使用时才加载,且只能SingletonHolder类能访问
//特别注意:static域中修改共享变量是线程安全的,由JVM保障
     static Singleton INSTANCE = new Singleton();
   }
  public static Singleton getInstance() {
     return SingletonHolder.INSTANCE;
   }
}


2.3双重检测

普通双重检测:

public class Singleton {
  private static Singleton instance = null;
  private Singleton() { }
  public static Singleton getInstance() {
     if(instance == null) {
        synchronzied(Singleton.class) {
           if(instance == null) {
               instance = new Singleton();
           }
        }
     }
     return instance;
   }
}
缺点:指令重排问题,参考 我的这篇文章

解决方案:

针对instance实例变量用volatile修饰就可以了,volatile修饰的话就可以确保instance = new Singleton();对应的指令不会重排序:

public class Singleton {
  private static volatile Singletoninstance = null;  //以volatile关键字修饰防止指令重排
  private Singleton() { }  //构造函数为私有,防止被实例化
  public static Singleton getInstance() {
     if(instance == null) {     //双重检测
        synchronzied(Singleton.class) {
           if(instance == null) {
               instance = new Singleton();
           }
        }
     }
     return instance;
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值