欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java编程WeakHashMap实例解析

程序员文章站 2023-01-03 18:51:22
简述: 《thinking in java》第4版 p519 页 weakhashmap一章读书笔记 weakhashmap 用来保存weakreference,这...

简述:

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实例解析

总结

以上就是本文关于java编程weakhashmap实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!