【進階java程式員應該知道的小知識】 WeakHashMap

來源:互聯網
上載者:User

標籤:weak   hashmap   弱引用雜湊表   java   程式員   

本篇宗旨:simple & stupid WeakHashMap (弱引用的雜湊表)

Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.

基於弱引用的鍵Key實現的雜湊表,當GC發現某個弱引用的鍵可以回收時,索引值對<K,V>也會從表中移除。

用法:
  private static final WeakHashMap<Configuration,Object> REGISTRY =     new WeakHashMap<Configuration,Object>();
用途:

當需要做緩衝Cache時,如果不及時釋放一些緩衝中的不用的對象所佔用的記憶體,是一種對記憶體的浪費,因為緩衝的生命週期往往和容納此緩衝的組件的生命週期一樣長。

如果考慮用雜湊表來做<Key,Value>式的緩衝,將一個不再使用的對象從雜湊表移除的方式就是手工編寫代碼移除。這很麻煩,也容易忘記。

這種情況,就推薦使用WeakHashMap
Keyweak-reachable 弱可達狀態時,KeyValue都會從表中移除。

【著作權@foreach_break 轉載請註明出處 部落格地址http://blog.csdn.net/gsky1986】

【進階java程式員應該知道的小知識】 WeakHashMap

聯繫我們

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