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

来源:互联网 发布:网页设计排版软件 编辑:程序博客网 时间:2024/06/07 05:54

转载请注明出处: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. }  
0 0
原创粉丝点击