WeakHashMap 笔记

来源:互联网 发布:大疆 知乎 编辑:程序博客网 时间:2024/06/07 20:04

简述:

《Thinking in Java》第4版 P519 页 WeakHashMap一章读书笔记


WeakHashMap 用来保存WeakReference,这一结构云逊垃圾回收器自动清理键和值

在添加键和值的操作时,映射会自动使用WeakReference包装它们,

见jdk源代码,

    public V put(K key, V value) {        Object k = maskNull(key);        int h = hash(k);        Entry<K,V>[] tab = getTable();        int i = indexFor(h, tab.length);        for (Entry<K,V> e = tab[i]; e != null; e = e.next) {            if (h == e.hash && eq(k, e.get())) {                V oldValue = e.value;                if (value != oldValue)                    e.value = value;                return oldValue;            }        }        modCount++;        Entry<K,V> e = tab[i];        tab[i] = new Entry<>(k, value, queue, h, e);        if (++size >= threshold)            resize(tab.length * 2);        return null;    }


其中new Entry<>(k, value, queue, h, e)一行使用了ReferenceQueue

    /**     * Reference queue for cleared WeakEntries     */    private final ReferenceQueue<Object> queue = new ReferenceQueue<>();

点入new Entry的构造函数,进入super顶层可以看到,

    /**     * Creates a new weak reference that refers to the given object and is     * registered with the given queue.     *     * @param referent object the new weak reference will refer to     * @param q the queue with which the reference is to be registered,     *          or <tt>null</tt> if registration is not required     */    public WeakReference(T referent, ReferenceQueue<? super T> q) {        super(referent, q);    }
这里new Entry同时也构造出来了一个WeakRefence对象


测试:

package com.anialy.test.data_structure.map;import java.util.Iterator;import java.util.WeakHashMap;public class WeakHashMapTest {public static void main(String[] args) {WeakHashMap wmap = new WeakHashMap<String, Object>();final int SIZE = 10;String[] str = new String[SIZE];for(int i=0; i<SIZE; i++){String key = Integer.toString(i);String value = Integer.toString(i);// 每隔3个保留一个引用if(i % 3 == 0)str[i] = key;wmap.put(key, value);}System.gc();Iterator iter = wmap.keySet().iterator();while(iter.hasNext()){System.out.println(wmap.get(iter.next()));}}}


可以预料到,部分由于String[] 保留了弱引用,所以输出都是间隔3的














0 0
原创粉丝点击