WeakHashMap的使用
来源:互联网 发布:淘宝分享社区 编辑:程序博客网 时间:2024/04/30 13:06
HashMap相信大家都知道,而且应用得非常熟练,但是WeakHashMap不知道有多少人用过,是怎么使用的。最近在看源码的时候发现了WeakHashMap,就想看看这个到底和HashMap有什么不同。
public class WeakHashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
HashMap比WeakHashMap多实现了Cloneable和Serializable,HashMap让开发者能够去做序列化和反序列化的操作,即可用作为和数据库进行交换的对象。分析WeakHashMap的源码知道它采用的是弱引用的Entry<k,v>进行存储键值对。
/** * The entries in this hash table extend WeakReference, using its main ref * field as the key. */ private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>
那么弱引用关系和强引用关系到底有什么不同呢?看下面代码
public static void main(String[] args) { Map<Thread, String> weakHashMap = new WeakHashMap<Thread, String>(); Thread thread1 = new Thread(); Thread thread2 = new Thread(); weakHashMap.put(thread1, "thread1"); weakHashMap.put(thread2, "thread2"); thread1 = null; System.gc(); for(Entry<Thread, String> entry:weakHashMap.entrySet()){ System.out.println(entry.getValue()); } Map<Thread, String> hashMap = new HashMap<Thread, String>(); Thread thread3 = new Thread(); Thread thread4 = new Thread(); hashMap.put(thread3, "thread3"); hashMap.put(thread4, "thread4"); thread3 = null; System.gc(); for(Entry<Thread, String> entry:hashMap.entrySet()){ System.out.println(entry.getValue()); } }
这里我主动的用垃圾回收进行了处理,得出的结果是:
thread2thread4thread3
可以看出WeakHashMap中的thread1被垃圾回收了。但是HashMap的thread3却没有回收。弱引用关系当垃圾回收发生的时候,如果键为null那么就会被回收。
0 0
- WeakHashMap的使用
- WeakHashMap的使用
- WeakHashMap的使用场景
- Java WeakHashMap使用陷阱
- java WeakHashMap 使用
- weakhashmap使用原理
- 对WeakHashMap的使用不慎导致内存溢出分析
- WeakHashMap的神话
- WeakHashMap的神话
- WeakHashMap HashMap的区别
- WeakHashMap的一点理解
- WeakHashMap的基本使用方法
- WeakHashMap的用法
- WeakHashMap的理解
- WeakHashMap的一些理解
- WeakHashMap的Weak原理
- WeakHashMap的实现原理
- WeakHashMap存在的原因
- 第X大的数
- 广度优先搜索--BFS
- c/cpp中生成随机数
- 第十四周拓展项目1—数组大折腾(5)
- 文章标题
- WeakHashMap的使用
- 努力!
- 【C++】【格式】c++ 如何读入一行字符串
- 软件测试(第2版)_Paul学习07_01——Ch7基于决策表的测试_01
- 汽车产业的变革
- Servlet生命周期
- 阶乘质因数分解
- 诗词格律与创作
- Linux 下的udp通信