本篇宗旨: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】