关于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判断能拦截第一个获得对象锁线程以外的线程。

 

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

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM