雙重檢查
雙重檢查應用實例
代碼演示:
class Singleton{private static volatile Singleton singleton;private Singleton(){}// 提供一個靜態公有方法public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}// 同步代碼,效率是比較低的// 只是在判斷外就走過了}return instance;}
}
Java并發編程:volatile關鍵字解析
優缺點說明
-
double-check 概念是多線程開發中常使用到的,如代碼中所示,我們進行了兩次
if(singleton == null)
檢查,這樣就可以保證線程安全了 -
這樣,實例化代碼只用執行一次,后面再次訪問時候,判斷
if(singleton==null)
,
直接return實例化對象,也避免的反復進行方法同步. -
線程安全;延遲加載;效率較高
-
結論:在實際開發中,推薦 使用這種單例設計模式
更多:http://victorfengming.gitee.io/design_pattern/