標籤:
最簡單的單例「餓漢式」?
public class Singleton{
private static Singleton instance=new Singleton();
? ? //other fields
? ? private Singleton(){}
? ? public static Singleton getInstance(){
? ? ? ? ?return instance;
? ? }
? ? //other methods
}
出於效能等方面的考慮,希望延遲執行個體化單例對象(static 屬性在載入類時會被初始化),方案二應運而生,稱之為「懶漢式」
public class Singleton {
private static Singleton instance=null;
// 私人構造方法,防止從外部使用 new 方法建立對象
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
不幸的是,在高並發的環境中,getInstance()方法返回了多個指向不同的該類執行個體,也就是說:線程不安全。
安全執行緒寫法A
public class Singleton {
private static Singleton instance=null;
// 私人構造方法,防止從外部使用 new 方法建立對象
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
方案A中雖然實現了多線程的安全訪問,但在多線程高並發訪問情況下,加上 synchronized關鍵字會使得效能大不如前。
安全執行緒寫法B
public class Singleton {
private static volatile Singleton instance=null;
// 私人構造方法,防止從外部使用 new 方法建立對象
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class){
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
方案B,我們稱之為 Double-Checked Locking (雙重檢查加鎖)模式。在此方案中,還是使用 synchronized,只不過這次只是保證執行個體化的這段邏輯被一個線程執行。
前述的方法都存在小小的缺陷,有沒有一種既能實現消極式載入,又能實現安全執行緒的方案呢
終極方案
public class Singleton{
private Singleton(){}
private static class LazyHolder{
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return LazyHodler.instance;
}
}
單例(Singleton)模式