zoukankan      html  css  js  c++  java
  • 单例模式中 的 双重检查锁 概念与用法

    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;
         }
     }
  • 相关阅读:
    Ubuntu18.04+CUDA+CUDNN+Pytorch环境配置
    VIM入门必读(转)
    简述C和C++的学习历程(转)
    队列
    排序实现
    十进制转二进制
    北邮1467二叉树题引起的思考
    计算机是如何启动的?
    c语言字符串操作实现
    北邮机试——huffman权值问题
  • 原文地址:https://www.cnblogs.com/mryangbo/p/10835912.html
Copyright © 2011-2022 走看看