亲宝软件园·资讯

展开

Java编程WeakHashMap Java编程WeakHashMap实例解析

anialy 人气:0
想了解Java编程WeakHashMap实例解析的相关内容吗,anialy在本文为您仔细讲解Java编程WeakHashMap的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java,weakhashmap,java,hashmap实例,weakhashmap,缓存,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实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

加载全部内容

相关教程
猜你喜欢
用户评论