標籤: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。
當Key是weak-reachable 弱可達狀態時,Key和Value都會從表中移除。
【著作權@foreach_break 轉載請註明出處 部落格地址http://blog.csdn.net/gsky1986】
【進階java程式員應該知道的小知識】 WeakHashMap