【高级java程序员应该知道的小知识】 WeakHashMap
本篇宗旨: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发现某个弱引用的键可以回收时,键值对也会从表中移除。
用法:
private static final WeakHashMap REGISTRY = new WeakHashMap();
用途:
当需要做缓存Cache时,如果不及时释放一些缓存中的不用的对象所占用的内存,是一种对内存的浪费,因为缓存的生命周期往往和容纳此缓存的组件的生命周期一样长。
如果考虑用哈希表来做式的缓存,将一个不再使用的对象从哈希表移除的方式就是手工编写代码移除。这很麻烦,也容易忘记。
这种情况,就推荐使用WeakHashMap。
当Key是weak-reachable 弱可达状态时,Key和Value都会从表中移除。
【版权所有@foreach_break 转载请注明出处 博客地址http://blog.csdn.net/gsky1986】
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
