雙重檢查 單例模式

單例模式

/**
 * @description: 
 * 單例1 懶漢模式 double check
 * @author: brave.chen
 * @create: 2020-03-07 13:31
 **/
public class SingleDecl {
    private static  SingleDecl singleDecl;

    private SingleDecl() {
    }
    
    public static SingleDecl getInstance(){
        if(singleDecl == null){
            synchronized (SingleDecl.class){
                if(singleDecl == null){
                    singleDecl = SingleDecl.getInstance(); 
                }
            }
        }
        return singleDecl;
    }
}

上述代碼并不是線程安全的
因為singleDecl = SingleDecl.getInstance();這部分代碼并不是原子性的,
這個操作有很多步

   // 創(chuàng)建 Cache 對象實例,分配內(nèi)存
       0: new           #5                  // class com/query/Cache
       // 復(fù)制棧頂?shù)刂罚⒃賹⑵鋲喝霔m?       3: dup
    // 調(diào)用構(gòu)造器方法,初始化 Cache 對象
       4: invokespecial #6                  // Method "<init>":()V
    // 存入局部方法變量表
       7: astore_1
時序圖

如果遇到這種情況 那么線程2就會返回null。

如何解決

/**
 * @description: 
 * 單例1 懶漢模式 double check
 * @author: brave.chen
 * @create: 2020-03-07 13:31
 **/
public class SingleDecl {
    private volatile static  SingleDecl singleDecl;

    private SingleDecl() {
    }
    
    public static SingleDecl getInstance(){
        if(singleDecl == null){
            synchronized (SingleDecl.class){
                if(singleDecl == null){
                    singleDecl = SingleDecl.getInstance(); 
                }
            }
        }
        return singleDecl;
    }
}

加了 volatile 關(guān)鍵字后
volatile 作用
正確的雙重檢查鎖定模式需要需要使用 volatile。volatile主要包含兩個功能。

保證可見性。使用 volatile 定義的變量,將會保證對所有線程的可見性。
禁止指令重排序優(yōu)化。
由于 volatile 禁止對象創(chuàng)建時指令之間重排序,所以其他線程不會訪問到一個未初始化的對象,從而保證安全性。

注意,volatile禁止指令重排序在 JDK 5 之后才被修復(fù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容