lazy初始化和線程安全的單例模式


1.雙檢鎖/雙重校驗鎖(DCL,即 double-checked locking)

JDK 版本:JDK1.5 起

是否 Lazy 初始化:

是否多線程安全:

實現難度:較復雜

描述:這種方式采用雙鎖機制,安全且在多線程情況下能保持高性能。
getSingleton() 的性能對應用程序很關鍵。

 

package com.advance.singleton;

/**
 * @Auther: 谷天樂
 * @Date: 2018/9/17 21:02
 * @Description:
 */

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

    public static void main(String[] args) {
        Singleton s1 = getSingleton();
        Singleton s2 = getSingleton();
        System.out.println(s1==s2);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM