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); } }