實現Singleton 模式 六種實現方式

2021-09-30 15:52:29 字數 1478 閱讀 9669

public static class singleton

public static singleton getinstance()

}

public static class singleton

public static singleton getinstance()

return instance;

}}

懶漢模式在方法被呼叫後才建立物件,以時間換空間,在多執行緒環境下存在風險。

public static class singleton

public static synchronized singleton getinstance()

return instance;

}}

public static class singleton

private singleton

public static singleton getinstance()

}

public static class singleton

public static singleton getinstance()

}} return instance;

}}

dcl模式的優點就是,只有在物件需要被使用時才建立,第一次判斷 instance == null為了避免非必要加鎖,當第一次載入時才對例項進行加鎖再例項化。這樣既可以節約記憶體空間,又可以保證執行緒安全。但是,由於jvm存在亂序執行功能,dcl也會出現執行緒不安全的情況。具體分析如下:

instance = new singleton();

這個步驟,其實在jvm裡面的執行分為三步:

1.在堆記憶體開闢記憶體空間。

2.在堆記憶體中例項化singleton裡面的各個引數。

3.把物件指向堆記憶體空間。

由於jvm存在亂序執行功能,所以可能在2還沒執行時就先執行了3,如果此時再被切換到該執行緒上,由於執行了3,instance 已經非空了,會被直接拿出來用,這樣的話,就會出現異常。這個就是著名的dcl失效問題。

不過在jdk1.5之後,官方也發現了這個問題,故而具體化了volatile,即在jdk1.6及以後,只要定義為private volatile static singleton instance = null;就可解決dcl失效問題。volatile確保instance每次均在主記憶體中讀取,這樣雖然會犧牲一點效率,但也無傷大雅。

public static class singleton

private singleton

public static singleton getinstance()

}

六種單列模式

確保某乙個類只有乙個例項.1 餓漢式單列 public class singleone 構造方法私有 禁止建立 private singleone 2 懶漢式單列 public class singletwo 同步方法 每次呼叫都同步 消耗資源 public static synchronized ...

六種排序的C 實現

class sortnum 具體實現 view plain copy to clipboard print?include sortnum.h include iostream.h construction destruction sortnum sortnum sortnum sortnum 交換...

六種方式實現hibernate查詢

hibernate查詢的6種方法。分別是hql查詢 物件化查詢criteria方法,動態查詢detachedcriteria,例子查詢,sql查詢,命名查詢。1 hql查詢 hql是hibernate自己的一套查詢語言,於sql語法不同,具有跨資料庫的優點。示例 static void query ...