單例(Singleton)模式

來源:互聯網
上載者:User

標籤:

最簡單的單例「餓漢式」?

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)模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.