Java编程WeakHashMap实例解析
作者:anialy
这篇文章主要介绍了Java编程WeakHashMap实例解析,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
简述:
《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的
总结
以上就是本文关于Java编程WeakHashMap实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!