1.WeakHashMap继承了AbstractMap,实现了Map接口
public class WeakHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>
2. (01) 新建WeakHashMap,将“键值对”添加到WeakHashMap中。WeakHashMap是通过数组table保存Entry(键值对);每一个Entry实际上是一个单向链表,即Entry是键值对链表。
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
V value;
final int hash;
Entry<K,V> next;
/**
* Creates new entry.
*/
Entry(Object key, V value,
ReferenceQueue<Object> queue,
int hash, Entry<K,V> next) {
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
}
super(key, queue); key 表示将原始key对象包装成了WeakReference弱引用对象;
(02)当某“弱键”不再被其它对象引用,并被GC回收时。在GC回收该“弱键”时,这个“弱键”也同时会被添加到ReferenceQueue(queue)队列中。
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();//用来内存回收
当被WeakReference包装的键值对象被垃圾回收之后,对应的Entry对象会被添加到queue引用队列中,如果在queue中存在某个键值,会同步删除WeakHashMap中该键值所对应的节点
3.弱键检测:
public class weakHash {
public static void main(String[] args) {
WeakHashMap<String,String> map = new WeakHashMap<>();
String s1 = new String("one");
String s2 = new String("two");
String s3 = new String("three");
map.put(s1,"one");
map.put(s2,"two");
map.put(s3,"three");
System.out.println("map: "+ map);
map.remove("three");
//弱键测试
s1 = null;
System.gc();//垃圾回收
Iterator<Map.Entry<String,String>> itr = map.entrySet().iterator();
while(itr.hasNext()){
Map.Entry<String,String> entry = itr.next();
System.out.println("key: "+entry.getKey()+" value: "+entry.getValue());
}
System.out.println("回收后,map的size: "+map.size());
}
}
运行结果:
map: {three=three, one=one, two=two}
key: two value: two
回收后,map的size: 1