關於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