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
原创粉丝点击