"Thinking in Java" 4th edition P519 page WeakHashMap Chapter Reading Notes
WeakHashMap is used to save WeakReference, a structure called Yunxun garbage collector automatically cleans up keys and values.
When adding keys and values, the mapping will automatically wrap them with WeakReference.
See jdk source code,
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;} The new Entry<>(k, value, queue, h, e) uses ReferenceQueue
/** * Reference queue for cleared WeakEntries */ private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
Click the constructor of new Entry , enter the top level of super to see.
/** * Creates a new weak reference that refers to the given object and is * registered with the given queue. * * @param reference 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 reference, ReferenceQueue<? super T> q) { super(referent, q); } Here new Entry also constructs a WeakRefence object
test:
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);// Keep a reference every 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()));}}}It can be expected that, in part, since String[] retains weak references, the outputs are all interval 3.
The above is all the content of this article about the analysis of the WeakHashMap instance of Java programming, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!