2011-06-22 32 views
3

今天我發現this blog post,它討論了在緩存上使用WeakHashMap的用法。它被一個事實所吸引,即不是值,而是鍵被存儲爲弱引用,並且當引用不再活動時,整個鍵 - 值對將從WeakHashMap中移除。因此,這將導致以下情況發生:WeakHashMap - 它的目的是什麼以及它應該如何正確使用

WeakHashMap map = new WeakHashMap(); 
SomeClass myReference1 = .... 
map.put(new Long(10), myReference1); 
// do some stuff, but keep the myReference1 variable around! 
SomeClass myReference2 = map.get(new Long(10)); // query the cache 
if (myReference2 == null) { 
    // this is likely to happen because the reference to the first new Long(10) object 
    // might have been garbage-collected at this point 
} 

我很好奇,什麼場景,然後將採取WeakHashMap類的優勢在哪裏?

+0

自動裝箱,你沒有顯式調用'新龍(10)'。這就足夠了:'map.get(10L);' –

+0

可能重複[你什麼時候使用WeakHashMap或WeakReference?](http://stackoverflow.com/questions/154724/when-would-you-use- a-weakhashmap-or-a-weakreference) –

+1

@Matt Ball,這不是重複的,因爲問題是爲WeakHashMap獲取一些用例,而不是將它與其他構造進行比較。 –

回答

3

當您要將元數據附加到您不控制生命週期的對象時。一個常見的例子是ClassLoader,儘管必須小心避免創建一個value-> key引用循環。

+0

那麼那個對象就是我猜想的弱哈希映射中的關鍵? –

+0

+1的警告。如果你有價值 - >關鍵循環,你需要的是[ephemeron對](http://en.wikipedia.org/wiki/Ephemeron)。 –

+0

感謝您的信息,現在我看到了WeakHashMap的用途。它實際上是一個非常聰明的解決方案來存儲元數據,因爲由於關鍵對象不可用,將所有關聯的元數據自動處理只是時間問題。 –

1

有很多用途,但其中一個非常重要的是當你想要鍵入Class。保持對Class實例的強烈參考可以綁定整個類加載器。

另外,番石榴具有更完整的一套非強參考映射構造。

+0

是的,一個好點。也許我可以自己使用它來緩存一些我通過反射檢索的類型的元數據(以避免重複反射調用)。 –

1

我跑的樣本代碼來了解HashMap和WeakHashMap中的區別,希望它可以幫助

 Map hashMap= new HashMap(); 
     Map weakHashMap = new WeakHashMap(); 

     String keyHashMap = new String("keyHashMap"); 
     String keyWeakHashMap = new String("keyWeakHashMap"); 

     hashMap.put(keyHashMap, "helloHash"); 
     weakHashMap.put(keyWeakHashMap, "helloWeakHash"); 
     System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap")); 

     keyHashMap = null; 
     keyWeakHashMap = null; 

     System.gc(); 

     System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap")); 

輸出將是:

Before: hash map value:helloHash and weak hash map value:helloWeakHash 
After: hash map value:helloHash and weak hash map value:null 
相關問題