《劍指Offer》——Singleton(Java版)

來源:互聯網
上載者:User

標籤:研究   資源   建構函式   let   原子操作   錯誤   使用   ons   return   

1.單例模式的定義

  單例模式確保某個類只有一個執行個體,而且自行執行個體化並向整個系統提供這個執行個體。

 

2.單例模式的特點

  單例類只能有一個執行個體。

  單例類必須自己建立自己的唯一執行個體。

  單例類必須給所有其他對象提供這一執行個體。

 3.單例模式的Java代碼

  單例模式分為懶漢式(需要才去建立對象)和餓漢式(建立類的執行個體時就去建立對象)。

 

4.餓漢式

  在靜態代碼塊執行個體對象

//在靜態代碼塊執行個體對象public class Singleton {
private static Singleton singleton; static { singleton = new Singleton(); } public static Singleton getInstance() { return singleton; } private Singleton() {}}

 

  屬性執行個體化對象

//餓漢模式:安全執行緒,耗費資源。class SingletonHungry {
private static final SingletonHungry singletontest = new SingletonHungry(); public static SingletonHungry getSingletontest() { return singletontest; } private SingletonHungry() {}}

 

以上,餓漢式只要調用該類,就會執行個體化一個對象,非常的佔用資源。

 

5.懶漢式

  非安全執行緒,只有加入線程鎖(synchronized關鍵字)來保證安全執行緒。

//懶漢模式:需加入線程鎖(synchronized 關鍵字),保證安全class SingletonSlacker1 {
private static SingletonSlacker1 singleton; public synchronized static SingletonSlacker1 getInstance() { if (singleton == null) { singleton = new SingletonSlacker1(); } return singleton; } private SingletonSlacker1() {}}

當然,該方式,雖然保證了線程的安全,但是只能有一個線程調用,其他線程必須等待。

 

  安全執行緒:雙重檢查鎖(同步代碼塊)

//懶漢模式:加入雙重鎖class SingletonSlacker2 {
private static SingletonSlacker2 singleton; public synchronized static SingletonSlacker2 getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new SingletonSlacker2(); } } } return singleton; } private SingletonSlacker2() { }}

 

 6.指令重排序

  其實建立一個對象,往往包含三個過程。 
  對於singleton = new Singleton(),這不是一個原子操作,在 JVM 中包含的三個過程。

    1、給 singleton 分配記憶體

    2、調用 Singleton 的建構函式來初始化成員變數,形成執行個體

    3、將singleton對象指向分配的記憶體空間(執行完這步 singleton才是非 null 了)

 

  針對JVM中的 指令重排序,我們可以使用 Volatile關鍵字來保證安全執行緒。

class SingletonVolatile{    //volatile的作用是 :保證可見度,禁止重排序,但不能保證原子性。    private volatile static SingletonVolatile singleton;    public synchronized static SingletonVolatile getInstance(){        if(singleton==null){            synchronized (SingletonVolatile.class){                if (singleton==null){                    singleton= new SingletonVolatile();                }            }        }        return singleton;    }    private SingletonVolatile(){}}

 

 

研究不深,剛學習java,如果有什麼差錯,還望指出錯誤,共同改進。

 

github地址:https://github.com/Yahuiya/PersonalNotes

 

《劍指Offer》——Singleton(Java版)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.