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;
         }
     }
  • 相关阅读:
    Linux就该这么学--Shell脚本基本应用
    Linux就该这么学--了解Shell脚本
    Linux就该这么学--命令集合11(配置系统相关信息)
    解決 centos -bash: vim: command not found
    Linux就该这么学--命令集合10(vim编辑器)
    Linux就该这么学--命令集合9(环境变量)
    html5 浏览器端数据库
    加密技术---仿射密码
    数组的运用、排序
    面试题参考
  • 原文地址:https://www.cnblogs.com/mryangbo/p/10835912.html
Copyright © 2011-2022 走看看