码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-05-09 00:34:25      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:instance   checked   pre   multiple   read   init   section   它的   imu   

 

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;
     }
 }

 

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

标签:instance   checked   pre   multiple   read   init   section   它的   imu   

原文地址:https://www.cnblogs.com/mryangbo/p/10835912.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!