温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java编程WeakHashMap的示例分析

发布时间:2021-08-11 10:47:26 来源:亿速云 阅读:116 作者:小新 栏目:编程语言

这篇文章主要介绍Java编程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的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI