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


    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;
         }
     }
  • 相关阅读:
    认识Java数组(一)
    Java之定时任务详解
    Java三大特征之多态(三)
    Java三大特征之继承(二)
    Java三大特征之封装(一)
    eclipse常用快捷键汇总
    JDK动态代理
    Java代理模式——静态代理模式
    CRISPR/Cas9基因敲除原理及实验建议
    MicroRNA 详解
  • 原文地址:https://www.cnblogs.com/mryangbo/p/10835912.html
Copyright © 2020-2023  润新知