java并发的线程安全单例模式

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

1、饿汉式

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Singleton {  
  2.   private final static Singleton INSTANCE = new Singleton();  
  3.   private Singleton() { }  
  4.   public static Singleton getInstance() {  
  5.      return INSTANCE;  
  6.    }  
  7. }   
缺点:类加载时即分配空间,若不使用则较为占用内存空间。


2、懒汉式

2.1普通加锁模式

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Singleton {  
  2.   private static Singleton instance = null;  
  3.   private Singleton() { }  
  4.    
  5.   public static synchronized Singleton getInstance() {  
  6.      if(instance == null) {  
  7.         instance = new Singleton();  
  8.      }  
  9.      return instance;  
  10.    }  
  11. }   
缺点:每个线程调用getInstance都要加锁,效率低,我们想要只在第一次调用getInstance时加锁,请看下面的双重检测方案


2.2占位符模式(推荐)

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

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Singleton {  
  2.   private Singleton() { }  
  3.    privatestatic class SingletonHolder {    
  4. //内部类,第一次使用时才加载,且只能SingletonHolder类能访问  
  5. //特别注意:static域中修改共享变量是线程安全的,由JVM保障  
  6.      static Singleton INSTANCE = new Singleton();  
  7.    }  
  8.   public static Singleton getInstance() {  
  9.      return SingletonHolder.INSTANCE;  
  10.    }  
  11. }  


2.3双重检测

普通双重检测:

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Singleton {  
  2.   private static Singleton instance = null;  
  3.   private Singleton() { }  
  4.   public static Singleton getInstance() {  
  5.      if(instance == null) {  
  6.         synchronzied(Singleton.class) {  
  7.            if(instance == null) {  
  8.                instance = new Singleton();  
  9.            }  
  10.         }  
  11.      }  
  12.      return instance;  
  13.    }  
  14. }  
缺点:指令重排问题,参考 我的这篇文章

解决方案:

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

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class Singleton {  
  2.   private static volatile Singletoninstance = null;  //以volatile关键字修饰防止指令重排  
  3.   private Singleton() { }  //构造函数为私有,防止被实例化  
  4.   public static Singleton getInstance() {  
  5.      if(instance == null) {     //双重检测  
  6.         synchronzied(Singleton.class) {  
  7.            if(instance == null) {  
  8.                instance = new Singleton();  
  9.            }  
  10.         }  
  11.      }  
  12.      return instance;  
  13.    }  
  14. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值