懶漢單例模式多線程問題

單例模式:
懶漢式在多線程下的可能被多次賦值的情況:

LazySingleton.java

public class LazySingleton {
    private static LazySingleton lazySingleton ;

    private LazySingleton() {

    }

    public static LazySingleton getInstance() {
        if (lazySingleton == null) {
            lazySingleton = new LazySingleton();
        }
        return lazySingleton;
    }
}

出現原因:可能會有多個線程同時通過 lazySingleton == null 判斷條件,這樣會同時對lazySingleton賦了兩次值,在某些情況下可能會不被允許。解決方法:加同步鎖,但是這樣開銷會比較大,于是有了雙重檢查的這種方式,但是注意添加volatile防止指令重排序,

為什么雙重檢查鎖模式需要 volatile ?

不得不提的volatile及指令重排序(happen-before)

文中介紹了除了雙重檢查模式 還可使用局部變量的方式

雙重檢查方式

public class LazySingleton {
    private static volatile LazySingleton lazySingleton ;

    private LazySingleton() {

    }

    public static LazySingleton getInstance() {
        if (lazySingleton == null) {
            synchronized (LazySingleton.class) {
                if (lazySingleton == null) {
                    lazySingleton = new LazySingleton();
                }
            }
        }
        return lazySingleton;
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。