单例模式中 的 双重检查锁 概念与用法

public class Singleton {
    //私有的 静态的 本类属性
    private volatile static Singleton _instance;
    //私有化构造器
    private Singleton() {}
     /*
      * 1st version: creates multiple instance if two thread access
      * this method simultaneouslyX
      */
     public static Singleton getInstance() {
         if (_instance == null) {
             _instance = new Singleton();
         }
         return _instance;
     }
  
    /*
     * 2nd version : this definitely thread-safe and only
     * creates one instance of Singleton on concurrent environment
     * but unnecessarily expensive due to cost of synchronization
     * at every call.
     */
  
    public static synchronized Singleton getInstanceTS() {
        if (_instance == null) {
            _instance = new Singleton();
        }
        return _instance;
    }
  
    /*
     * 3rd version : An implementation of double checked locking of Singleton.
     * Intention is to minimize cost of synchronization and  improve performance,
     * by only locking critical section of code, the code which creates instance of Singleton class.
     * By the way this is still broken, if we don't make _instance volatile, as another thread can
     * see a half initialized instance of Singleton.
     */
    //双重检查锁:检查了2次;使用了一个锁
    //此处需要volatile修饰属性保证它的内存可见性??
     public static Singleton getInstanceDC() {
         if (_instance == null) {//第一次检查
             synchronized (Singleton.class) {
                 if (_instance == null) { //第二次检查   //线程1创建完对象后,线程会判断一次就不会创建对象了。解决了首次创建对象的唯一性问题。
                     _instance = new Singleton();
                 }
             }
         }
         return _instance;
     }
 }

猜你喜欢

转载自www.cnblogs.com/mryangbo/p/10835912.html
今日推荐