【轉】高併發狀況下的單例模式

若是在高併發時候,使用這種單例模式 
publci class Singleton{ 
     private static Singleton instance = null; 
     private Singleton(){} 

     public static Singleton getInstance(){ 
            if(instance == null){ 
                   instance = new Singleton(); 
            } 
            return instance; 
    } 

可能會出現多個指向改類的對象,這是什麼狀況呢? 

 
從上面圖能夠看到,在一、2狀況都沒有建立對象,到了3時候Thread1建立一個對象,而Thread2並不知道,因此在4的狀況下面Thread2也建立了對象,因此就出現該類不一樣對象,若是是使用C++語言實現這種模式,並且沒有手工去回收就可能出現內存泄露狀況。解決的方法是使用關鍵字synchronized代碼以下: 
publci class Singleton{ 
     private static Singleton instance = null; 
     private Singleton(){} 

     public static synchronized Singleton getInstance(){ 
            if(instance == null){ 
                   instance = new Singleton(); 
            } 
            return instance; 
    } 

這樣一來無論多少個線程訪問都是實現一個對象實例化了。可是若是使用該關鍵字可能性能方面有所下降,由於每次訪問時候都只能一個線程獲取到該對象,當出現多個線程訪問時候就會出現排隊等待的狀況,爲了解決這種狀況只須要在建立時候使用該關鍵字就能夠了 
publci class Singleton{ 
     private static Singleton instance = null; 
     private Singleton(){} 

     public static Singleton getInstance(){ 
            if(instance == null){ 
                   synchronized(Singleton.class){ 
                        if(instance == null) 
                        instance = new Singleton(); 
                   }           
             } 
            return instance; 
    } 

由於第一次使用該對象時候才須要檢查該對象是否已經建立了,而第二次檢查改對象是否爲空是爲了不一、2的狀況,由於無論是Thread1或者是Thread2拿到線程鎖都不會阻止另外的線程建立對象,由於到了2的狀況中,若是Thread1已經拿到線程鎖以後,建立對象可是到了Thread2獲取到線程鎖時候,也建立對象因此也會出現不一樣對象實例的狀況,這種兩次檢查叫作double click locking模式併發

相關文章
相關標籤/搜索