WeakValueHashMap源码

阅读更多

    JAVA内置提供了WeakHashMap,此map是基于key作为弱引用而设计的;通常情况下,我们还需要一种“弱”map,就是根据value而设计,即如果value的实际引用被回收时,map中也应该移除其对应的KV。

 

    WeakValueHashMap.java

import javax.annotation.concurrent.NotThreadSafe;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Author: liuguanqing
 * Date: 2019-06-12 11:23
 * 

* This Map will remove entries when the value in the map has been cleaned from garbage collection **/ @NotThreadSafe public class WeakValueHashMap extends AbstractMap implements Map { private Map> hash; private ReferenceQueue queue = new ReferenceQueue(); private void processQueue() { while (true) { WeakValueRef ref = (WeakValueRef) queue.poll(); if (ref == null) { break; } if (ref == hash.get(ref.key)) { hash.remove(ref.key); } } } public WeakValueHashMap() { hash = new HashMap(); } public WeakValueHashMap(int initialCapacity, float loadFactor) { hash = new HashMap(initialCapacity, loadFactor); } public WeakValueHashMap(int initialCapacity) { hash = new HashMap(initialCapacity); } public WeakValueHashMap(Map m) { this(Math.max(2 * m.size(), 11), 0.75f); putAll(m); } public int size() { processQueue(); return hash.size(); } public boolean isEmpty() { processQueue(); return hash.isEmpty(); } public boolean containsKey(Object key) { processQueue(); return hash.containsKey(key); } /** * 如果value引用已不存在,可能返回null * * @param key * @return */ public V get(Object key) { processQueue(); WeakReference ref = hash.get(key); return ref == null ? null : ref.get(); } public V put(K key, V value) { processQueue(); WeakReference ref = hash.put(key, WeakValueRef.create(key, value, queue)); return ref == null ? null : ref.get(); } public V remove(Object key) { processQueue(); WeakReference value = hash.remove(key); return value == null ? null : value.get(); } public void clear() { processQueue(); hash.clear(); } public Set entrySet() { processQueue(); return hash.entrySet(); } private static class WeakValueRef extends WeakReference { public K key; private WeakValueRef(K key, V val, ReferenceQueue q) { super(val, q); this.key = key; } private static WeakValueRef create(K key, V val, ReferenceQueue q) { if (val == null) { return null; } return new WeakValueRef(key, val, q); } } }

 

你可能感兴趣的:(WeakValueHashMap源码)