线程安全的单例模式(转载)

  原文查看这里

面试的时候,常常会被问到这样一个问题:请您写出一个单例模式(Singleton Pattern)吧。好吧,写就写,这还不容易。顺手写一个:

  1. public final class EagerSingleton  
  2. {  
  3.     private static EagerSingleton singObj = new EagerSingleton();  
  4.   
  5.     private EagerSingleton(){  
  6.     }  
  7.   
  8.     public static EagerSingleton getSingleInstance(){  
  9.        return singObj;
  10.     }  
  11. }  
    这种写法就是所谓的 饥饿模式 ,每个对象在没有使用之前就已经初始化了。这就可能带来潜在的性能问题:如果这个对象很大呢?没有使用这个对象之前,就把它加载到了内存中去是一种巨大的浪费。针对这种情况,我们可以对以上的代码进行改进,使用一种新的设计思想—— 延迟加载(Lazy-load Singleton) 。
  1. public final class LazySingleton  
  2. {  
  3.     private static LazySingleton singObj = null;  
  4.   
  5.     private LazySingleton(){  
  6.     }  
  7.   
  8.     public static LazySingleton getSingleInstance(){  
  9.         if(null == singObj ) singObj = new LazySingleton();
  10.           return singObj;
  11.     }  
  12. }  
    这种写法就是所谓的 懒汉模式 。它使用了延迟加载来保证对象在没有使用之前,是不会进行初始化的。但是,通常这个时候面试官又会提问新的问题来刁难一下。他会问:这种写法线程安全吗?回答必然是:不安全。这是因为在多个线程可能同时运行到第九行,判断singObj为null,于是同时进行了初始化。所以,这是面临的问题是如何使得这个代码线程安全?很简单,在那个方法前面加一个Synchronized就OK了。
  1. public final class ThreadSafeSingleton  
  2. {  
  3.     private static ThreadSafeSingleton singObj = null;  
  4.   
  5.     private ThreadSafeSingleton(){  
  6.     }  
  7.   
  8.     public static Synchronized ThreadSafeSingleton getSingleInstance(){  
  9.         if(null == singObj ) singObj = new ThreadSafeSingleton();
  10.             return singObj;
  11.     }  
  12. }  
    写到这里,面试官可能仍然会狡猾的看了你一眼,继续刁难到:这个写法有没有什么性能问题呢?答案肯定是有的! 同步的代价必然会一定程度的使程序的并发度降低 。那么有没有什么方法,一方面是线程安全的,有可以有很高的并发度呢?我们观察到,线程不安全的原因其实是在初始化对象的时候,所以,可以想办法把同步的粒度降低,只在初始化对象的时候进行同步。这里有必要提出一种新的设计思想—— 双重检查锁(Double-Checked Lock)。
  1. public final class DoubleCheckedSingleton  
  2. {  
  3.     private static DoubleCheckedSingletonsingObj = null;  
  4.   
  5.     private DoubleCheckedSingleton(){  
  6.     }  
  7.   
  8.     public static DoubleCheckedSingleton getSingleInstance(){  
  9.         if(null == singObj ) {
  10.               Synchronized(DoubleCheckedSingleton.class){
  11.                      if(null == singObj)
  12.                            singObj = new DoubleCheckedSingleton();
  13.               }
  14.          }
  15.        return singObj;
  16.     }  
  17. }  
     这种写法使得只有在加载新的对象进行同步,在加载完了之后,其他线程在第九行就可以判断跳过锁的的代价直接到第15行代码了。做到很好的并发度。
     至此,上面的写法一方面实现了Lazy-Load,另一个方面也做到了并发度很好的线程安全,一切看上很完美。这是,面试官可能会对你的回答满意的点点头。但是,你此时提出说,其实这种写法还是有问题的!!问题在哪里?假设线程A执行到了第9行,它判断对象为空,于是线程A执行到第12行去初始化这个对象,但初始化是需要耗费时间的,但是这个对象的地址其实已经存在了。此时线程B也执行到了第九行,它判断不为空,于是直接跳到15行得到了这个对象。但是,这个对象还 没有被完整的初始化! 得到一个没有初始化完全的对象有什么用!!关于这个Double-Checked Lock的讨论有很多,目前公认这是一个Anti-Pattern,不推荐使用!所以当你的面试官听到你的这番答复,他会不会被Hold住呢?
     那么有没有什么更好的写法呢?有!这里又要提出一种新的模式—— Initialization on Demand Holder. 这种方法使用内部类来做到延迟加载对象,在初始化这个内部类的时候,JLS(Java Language Sepcification)会保证这个类的线程安全。这种写法最大的美在于,完全使用了Java虚拟机的机制进行同步保证,没有一个同步的关键字。
  1. public class Singleton    
  2. {    
  3.     private static class SingletonHolder    
  4.     {    
  5.         public final static Singleton instance = new Singleton();    
  6.     }    
  7.    
  8.     public static Singleton getInstance()    
  9.     {    
  10.         return SingletonHolder.instance;    
  11.     }    
  12. }  
 
至此,本文完。提供一些链接For your reference:

-------------------------------------------华丽的分割线---------------------------------------------

对最后一个还不是很了解,应该是内部类掌握的还不是很清楚。

2013/03/18 更新

Initialzation on Demand Holder:

How it works

    The implementation relies on the well-specified initialization phase of execution within the Java Virtual Machine (JVM); see section 12.4 of Java Language Specification (JLS) for details.

    When the class Something is loaded by the JVM, the class goes through initialization. Since the class does not have any static variables to initialize, the initialization completes trivially. The static class definition LazyHolder within it is not initialized until the JVM determines that LazyHolder must be executed. The static class LazyHolder is only executed when the static method getInstance is invoked on the class Something, and the first time this happens the JVM will load and initialize the LazyHolder class. The initialization of the LazyHolder class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Something. Since the class initialization phase is guaranteed by the JLS to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization. And since the initialization phase writes the static variable INSTANCE in a serial operation, all subsequent concurrent invocations of the getInstance will return the same correctly initialized INSTANCE without incurring any additional synchronization overhead.

When to use it

    Use this pattern if the initialization of the class is expensive and it cannot be done safely at class-loading time and the initialization is highly concurrent. The crux of the pattern is the safe removal of the synchronization overhead associated with accessing a singleton instance.

When not to use it

    Avoid this idiom if the construction of INSTANCE can fail. If construction of INSTANCE fails, an invocation of Something.getInstance() will result in ajava.lang.ExceptionInInitializerError error. Handling, or mishandling, of these types of construction initialization failures is a common criticism of this idiom and the singleton pattern in general.

不闻不若闻之,闻之不若见之,见之不若知之,知之不若行之
原文地址:https://www.cnblogs.com/lauyu/p/5147071.html