码迷,mamicode.com
首页 > 编程语言 > 详细

【高级java程序员应该知道的小知识】 WeakHashMap

时间:2015-05-06 09:18:34      阅读:141      评论:0      收藏:0      [点我收藏+]

标签: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

标签:weak   hashmap   弱引用哈希表   java   程序员   

原文地址:http://blog.csdn.net/gsky1986/article/details/45521529

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!