• 关于Java单例模式中双重校验锁的实现目的及原理


    开始复习设计模式,一开始理解单例模式中的双重校验锁卡住了,想通了后就自己做了段思维导图来帮助自己理解。

    其实理解下来并不难,但还是记录下来帮助自己回忆和借机试试养成写博客的习惯~

    public class Singleton {
    
        private volatile static Singleton uniqueInstance;
    
        private Singleton() {
        }
    
        public static Singleton getUniqueInstance() {
            if (uniqueInstance == null) {
                synchronized (Singleton.class) {
                    if (uniqueInstance == null) {
                        uniqueInstance = new Singleton();
                    }
                }
            }
            return uniqueInstance;
        }
    }
    

      这是懒汉模式下双重校验锁下的简单代码

    public class Singleton {
    
        private volatile static Singleton uniqueInstance;
    
        private Singleton() {
        }
    
        public static Singleton getUniqueInstance() {
            if (uniqueInstance == null) {
                synchronized (Singleton.class) {
                    
                        uniqueInstance = new Singleton();
                    
                }
            }
            return uniqueInstance;
        }
    }
    

      懒汉模式下非双重校验锁下的简单代码

      差别在于第二个if判断能拦截第一个获得对象锁线程以外的线程。

      笔者顺便做了张思维导图截图,模板可能选得不好,还是要多练练哈。

      

  • 相关阅读:
    [译]理解 iOS 异常类型 <🌟>
    LeetCode 24. 两两交换链表中的节点
    解决The operation couldn’t be completed. Unable to log in with account
    <Typora> 常用操作快捷键
    LeetCode 23. 合并K个升序链表
    CSS盒子模型
    CCS属性
    CSS
    form表单
    html
  • 原文地址:https://www.cnblogs.com/ALego/p/11448563.html
Copyright © 2020-2023  润新知