2017-07-17 38 views
0

這裏是我帶有弱引用的單例類。帶有弱引用的Java單例

public class HandheldMapViewProvider { 

    private static WeakReference<HandheldMapViewProvider> mInstance = null; 

    private HandheldMapViewProvider(){ 

    } 

    public static synchronized WeakReference<HandheldMapViewProvider> getInstance(){ 
     if(mInstance == null){ 
     mInstance = new WeakReference<HandheldMapViewProvider>(new HandheldMapViewProvider()); 
     } 
     return mInstance; 
    } 

    public void onprint(String data){ 
     Log.D("TAG",data) 
    } 


} 

上述類的用法如下。

private WeakReference<HandheldMapViewProvider> hereMapViewProvider; 

public void onprint(){ 
    hereMapViewProvider = HandheldMapViewProvider.getInstance(); 
    hereMapViewProvider.get().onprint("somevalue"); 
} 

雖然第一次調用onprint方法的應用程序有時因get()爲空而崩潰。

任何想法,我做錯了。它並沒有一直髮生。

解決方法如下。

public static synchronized HandheldMapViewProvider getInstance(){ 
    HandheldMapViewProvider mapProvider = mInstance == null ? null :mInstance.get(); 

    if(mapProvider == null){ 

     mInstance = new WeakReference<HandheldMapViewProvider>(mapProvider =new HandheldMapViewProvider()); 
    } 

    return mapProvider; 

    } 
+0

您的主要錯誤是擺脫了singelton模式擺在首位。 https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons –

+0

從哪裏調用最後一段代碼? – 2017-07-17 13:19:35

+0

@EnamulHaque來自活動。大多數相同的代碼是完美的。有一段時間我變得空了。 –

回答

0

的問題是,你存儲HandheldMapViewProviderWeakReference。 垃圾回收器清除值,所以get()返回null。

要避免此行爲,只需刪除WeakRreference實施並將HandheldMapViewProvider存儲爲「常規」靜態字段。

0

弱引用對象,它不妨礙它們的對象被定型,定稿,然後回收。

垃圾收集器在某個時間點確定哪個對象很弱可達。那時它會原子地清除對該對象的所有弱引用,以及通過一系列強和軟引用可訪問該對象的任何其他弱可訪問對象的所有弱引用。同時它將宣佈所有以前弱可達的物體可以定型。

當我們使用弱引用時,在同一時間或稍後時間,它將使用參考隊列註冊的新清除的弱引用排入隊列。

這是發生形式垃圾收集器...所以我們不知道什麼時候會發生..

您可以通過使用try catch塊,以避免崩潰保存您的代碼..

public void onprint(){ 
    hereMapViewProvider = HandheldMapViewProvider.getInstance(); 
    try{ 
     hereMapViewProvider.get().onprint("somevalue"); 
    }catch(Exception e){ 
     Log.e("Err", e.toString()+""); 
    } 
} 
+0

這是解決方案的最終解決方案。 –

+0

嗨...還有其他解決方案嗎?如果有的話,請分享。 – 2017-07-27 11:03:43

+0

是的,將分享解決方案。 –

0

解決方法如下。

public static synchronized HandheldMapViewProvider getInstance(){ 
HandheldMapViewProvider mapProvider = mInstance == null ? null :mInstance.get(); 

if(mapProvider == null){ 

    mInstance = new WeakReference<HandheldMapViewProvider>(mapProvider =new 
    HandheldMapViewProvider()); 
} 

return mapProvider; 

}