• referenceQueue用法


    何为referenceQueue

    在java的引用体系中,存在着强引用,软引用,虚引用,幽灵引用,这4种引用类型。在正常的使用过程中,我们定义的类型都是强引用的,这种引用类型在回收中,只有当其它对象没有对这个对象的引用时,才会被GC回收掉。简单来说,对于以下定义:

    Object obj = new Object();
    Ref ref = new Ref(obj);
    

    在这种情况下,如果ref没有被GC,那么obj这个对象肯定不会GC的。因为ref引用到了obj。如果obj是一个大对象呢,多个这种对象的话,应用肯定一会就挂掉了。

    那么,如果我们希望在这个体系中,如果obj没有被其它对象引用,只是在这个Ref中存在引用时,就把obj对象gc掉。这时候就可以使用这里提到的Reference对象了。

    我们希望当一个对象被gc掉的时候通知用户线程,进行额外的处理时,就需要使用引用队列了。ReferenceQueue即这样的一个对象,当一个obj被gc掉之后,其相应的包装类,即ref对象会被放入queue中。我们可以从queue中获取到相应的对象信息,同时进行额外的处理。比如反向操作,数据清理等。

    使用队列进行数据监控

    一个简单的例子,通过往map中放入10000个对象,每个对象大小为1M字节数组。使用引用队列监控被放入的key的回收情况。代码如下所示:

    Object value = new Object();
    Map<Object, Object> map = new HashMap<>();
    for(int i = 0;i < 10000;i++) {
        byte[] bytes = new byte[_1M];
        WeakReference<byte[]> weakReference = new WeakReference<byte[]>(bytes, referenceQueue);
        map.put(weakReference, value);
    }
    System.out.println("map.size->" + map.size());
    

    这里使用了weakReference对象,即当值不再被引用时,相应的数据被回收。另外使用一个线程不断地从队列中获取被gc的数据,代码如下:

    Thread thread = new Thread(() -> {
        try {
            int cnt = 0;
            WeakReference<byte[]> k;
            while((k = (WeakReference) referenceQueue.remove()) != null) {
                System.out.println((cnt++) + "回收了:" + k);
            }
        } catch(InterruptedException e) {
            //结束循环
        }
    });
    thread.setDaemon(true);
    thread.start();
    

    完整示例:

    import java.lang.ref.ReferenceQueue;
    import java.lang.ref.WeakReference;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Test {
    	public static void main(String[] args) throws InterruptedException {
    		int _1M = 1024 * 1024;
    
    		ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
    		Thread thread = new Thread(() -> {
    			try {
    				int cnt = 0;
    				WeakReference<byte[]> k;
    				while ((k = (WeakReference) referenceQueue.remove()) != null) {
    					System.out.println((cnt++) + "回收了:" + k);
    				}
    			} catch (InterruptedException e) {
    				// 结束循环
    			}
    		});
    		thread.setDaemon(true);
    		thread.start();
    
    		Object value = new Object();
    		Map<Object, Object> map = new HashMap<>();
    		for (int i = 0; i < 10000; i++) {
    			byte[] bytes = new byte[_1M];
    			WeakReference<byte[]> weakReference = new WeakReference<byte[]>(bytes, referenceQueue);
    			map.put(weakReference, value);
    		}
    		System.out.println("map.size->" + map.size());
    	}
    }
    

    结果如下所示:

    ...
    9983回收了:java.lang.ref.WeakReference@1382f76
    9984回收了:java.lang.ref.WeakReference@551ad4
    9985回收了:java.lang.ref.WeakReference@17af971
    9986回收了:java.lang.ref.WeakReference@1e49cb2
    [GC (Allocation Failure)  5509K->1308K(15872K), 0.0001720 secs]
    [GC (Allocation Failure)  5490K->1309K(15872K), 0.0001729 secs]
    [GC (Allocation Failure)  5491K->1309K(15872K), 0.0001636 secs]
    map.size->10000
    

    在这次处理中,map并没有因为不断加入的1M对象由产生OOM异常,并且最终运行结果之后map中的确有1万个对象。表示确实被放入了相应的对象信息。不过其中的key(即weakReference)对象中的byte[]对象却被回收了。即不断new出来的1M数组被gc掉了。

    从命令行中,我们看到有9986个对象被gc,即意味着在map的key中,除了weakReference之外,没有我们想要的业务对象。那么在这样的情况下,是否意味着这9986个entry,我们认为就是没有任何意义的对象,那么是否可以将其移除掉呢。同时还期望size值可以打印出5,而不是10000.

    在类weakHashMap中的使用

    WeakHashMap就是这样的一个类似实现。
    weakHashMap即使用weakReference当作key来进行数据的存储,当key中的引用被gc掉之后,它会自动(类似自动)的方式将相应的entry给移除掉,即我们会看到size发生了变化。

    从简单来看,我们认为其中所有一个类似的机制从queue中获取引用信息,从而使得被gc掉的key值所对应的entry从map中被移除。这个处理点就在我们调用weakhashmap的各个处理点中,比如get,size,put等。简单点来说,就是在调用get时,weakHashMap会先处理被gc掉的key值,然后再处理我们的业务调用。

    WeakHashMap的源码进行解析如下:

    package java.util;
    import java.lang.ref.WeakReference;
    import java.lang.ref.ReferenceQueue;
    
    public class WeakHashMap<K,V>
        extends AbstractMap<K,V>
        implements Map<K,V> {
    
        // 默认的初始容量是16,必须是2的幂。
        private static final int DEFAULT_INITIAL_CAPACITY = 16;
    
        // 最大容量(必须是2的幂且小于2的30次方,传入容量过大将被这个值替换)
        private static final int MAXIMUM_CAPACITY = 1 << 30;
    
        // 默认加载因子
        private static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
        // 存储数据的Entry数组,长度是2的幂。
        // WeakHashMap是采用拉链法实现的,每一个Entry本质上是一个单向链表
        private Entry[] table;
    
        // WeakHashMap的大小,它是WeakHashMap保存的键值对的数量
        private int size;
    
        // WeakHashMap的阈值,用于判断是否需要调整WeakHashMap的容量(threshold = 容量*加载因子)
        private int threshold;
    
        // 加载因子实际大小
        private final float loadFactor;
    
        // queue保存的是“已被GC清除”的“弱引用的键”。
        // 弱引用和ReferenceQueue 是联合使用的:如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中
        private final ReferenceQueue<K> queue = new ReferenceQueue<K>();
    
        // WeakHashMap被改变的次数
        private volatile int modCount;
    
        // 指定“容量大小”和“加载因子”的构造函数
        public WeakHashMap(int initialCapacity, float loadFactor) {
            if (initialCapacity < 0)
                throw new IllegalArgumentException("Illegal Initial Capacity: "+
                                                   initialCapacity);
            // WeakHashMap的最大容量只能是MAXIMUM_CAPACITY
            if (initialCapacity > MAXIMUM_CAPACITY)
                initialCapacity = MAXIMUM_CAPACITY;
    
            if (loadFactor <= 0 || Float.isNaN(loadFactor))
                throw new IllegalArgumentException("Illegal Load factor: "+
                                                   loadFactor);
            // 找出“大于initialCapacity”的最小的2的幂
            int capacity = 1;
            while (capacity < initialCapacity)
                capacity <<= 1;
            // 创建Entry数组,用来保存数据
            table = new Entry[capacity];
            // 设置“加载因子”
            this.loadFactor = loadFactor;
            // 设置“WeakHashMap阈值”,当WeakHashMap中存储数据的数量达到threshold时,就需要将WeakHashMap的容量加倍。
            threshold = (int)(capacity * loadFactor);
        }
    
        // 指定“容量大小”的构造函数
        public WeakHashMap(int initialCapacity) {
            this(initialCapacity, DEFAULT_LOAD_FACTOR);
        }
    
        // 默认构造函数。
        public WeakHashMap() {
            this.loadFactor = DEFAULT_LOAD_FACTOR;
            threshold = (int)(DEFAULT_INITIAL_CAPACITY);
            table = new Entry[DEFAULT_INITIAL_CAPACITY];
        }
    
        // 包含“子Map”的构造函数
        public WeakHashMap(Map<? extends K, ? extends V> m) {
            this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, 16),
                 DEFAULT_LOAD_FACTOR);
            // 将m中的全部元素逐个添加到WeakHashMap中
            putAll(m);
        }
    
        // 键为null的mask值。
        // 因为WeakReference中允许“null的key”,若直接插入“null的key”,将其当作弱引用时,会被删除。
        // 因此,这里对于“key为null”的清空,都统一替换为“key为NULL_KEY”,“NULL_KEY”是“静态的final常量”。
        private static final Object NULL_KEY = new Object();
    
        // 对“null的key”进行特殊处理
        private static Object maskNull(Object key) {
            return (key == null ? NULL_KEY : key);
        }
    
        // 还原对“null的key”的特殊处理
        private static <K> K unmaskNull(Object key) {
            return (K) (key == NULL_KEY ? null : key);
        }
    
        // 判断“x”和“y”是否相等
        static boolean eq(Object x, Object y) {
            return x == y || x.equals(y);
        }
    
        // 返回索引值
        // h & (length-1)保证返回值的小于length
        static int indexFor(int h, int length) {
            return h & (length-1);
        }
    
        // 清空table中无用键值对。原理如下:
        // (01) 当WeakHashMap中某个“弱引用的key”由于没有再被引用而被GC收回时,
        //   被回收的“该弱引用key”也被会被添加到"ReferenceQueue(queue)"中。
        // (02) 当我们执行expungeStaleEntries时,
        //   就遍历"ReferenceQueue(queue)"中的所有key
        //   然后就在“WeakReference的table”中删除与“ReferenceQueue(queue)中key”对应的键值对
        private void expungeStaleEntries() {
            Entry<K,V> e;
            while ( (e = (Entry<K,V>) queue.poll()) != null) {
                int h = e.hash;
                int i = indexFor(h, table.length);
    
                Entry<K,V> prev = table[i];
                Entry<K,V> p = prev;
                while (p != null) {
                    Entry<K,V> next = p.next;
                    if (p == e) {
                        if (prev == e)
                            table[i] = next;
                        else
                            prev.next = next;
                        e.next = null;  // Help GC
                        e.value = null; //  "   "
                        size--;
                        break;
                    }
                    prev = p;
                    p = next;
                }
            }
        }
    
        // 获取WeakHashMap的table(存放键值对的数组)
        private Entry[] getTable() {
            // 删除table中“已被GC回收的key对应的键值对”
            expungeStaleEntries();
            return table;
        }
    
        // 获取WeakHashMap的实际大小
        public int size() {
            if (size == 0)
                return 0;
            // 删除table中“已被GC回收的key对应的键值对”
            expungeStaleEntries();
            return size;
        }
    
        public boolean isEmpty() {
            return size() == 0;
        }
    
        // 获取key对应的value
        public V get(Object key) {
            Object k = maskNull(key);
            // 获取key的hash值。
            int h = HashMap.hash(k.hashCode());
            Entry[] tab = getTable();
            int index = indexFor(h, tab.length);
            Entry<K,V> e = tab[index];
            // 在“该hash值对应的链表”上查找“键值等于key”的元素
            while (e != null) {
                if (e.hash == h && eq(k, e.get()))
                    return e.value;
                e = e.next;
            }
            return null;
        }
    
        // WeakHashMap是否包含key
        public boolean containsKey(Object key) {
            return getEntry(key) != null;
        }
    
        // 返回“键为key”的键值对
        Entry<K,V> getEntry(Object key) {
            Object k = maskNull(key);
            int h = HashMap.hash(k.hashCode());
            Entry[] tab = getTable();
            int index = indexFor(h, tab.length);
            Entry<K,V> e = tab[index];
            while (e != null && !(e.hash == h && eq(k, e.get())))
                e = e.next;
            return e;
        }
    
        // 将“key-value”添加到WeakHashMap中
        public V put(K key, V value) {
            K k = (K) maskNull(key);
            int h = HashMap.hash(k.hashCode());
            Entry[] tab = getTable();
            int i = indexFor(h, tab.length);
    
            for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
                // 若“该key”对应的键值对已经存在,则用新的value取代旧的value。然后退出!
                if (h == e.hash && eq(k, e.get())) {
                    V oldValue = e.value;
                    if (value != oldValue)
                        e.value = value;
                    return oldValue;
                }
            }
    
            // 若“该key”对应的键值对不存在于WeakHashMap中,则将“key-value”添加到table中
            modCount++;
            Entry<K,V> e = tab[i];
            tab[i] = new Entry<K,V>(k, value, queue, h, e);
            if (++size >= threshold)
                resize(tab.length * 2);
            return null;
        }
    
        // 重新调整WeakHashMap的大小,newCapacity是调整后的单位
        void resize(int newCapacity) {
            Entry[] oldTable = getTable();
            int oldCapacity = oldTable.length;
            if (oldCapacity == MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return;
            }
    
            // 新建一个newTable,将“旧的table”的全部元素添加到“新的newTable”中,
            // 然后,将“新的newTable”赋值给“旧的table”。
            Entry[] newTable = new Entry[newCapacity];
            transfer(oldTable, newTable);
            table = newTable;
    
            if (size >= threshold / 2) {
                threshold = (int)(newCapacity * loadFactor);
            } else {
                // 删除table中“已被GC回收的key对应的键值对”
                expungeStaleEntries();
                transfer(newTable, oldTable);
                table = oldTable;
            }
        }
    
        // 将WeakHashMap中的全部元素都添加到newTable中
        private void transfer(Entry[] src, Entry[] dest) {
            for (int j = 0; j < src.length; ++j) {
                Entry<K,V> e = src[j];
                src[j] = null;
                while (e != null) {
                    Entry<K,V> next = e.next;
                    Object key = e.get();
                    if (key == null) {
                        e.next = null;  // Help GC
                        e.value = null; //  "   "
                        size--;
                    } else {
                        int i = indexFor(e.hash, dest.length);
                        e.next = dest[i];
                        dest[i] = e;
                    }
                    e = next;
                }
            }
        }
    
        // 将"m"的全部元素都添加到WeakHashMap中
        public void putAll(Map<? extends K, ? extends V> m) {
            int numKeysToBeAdded = m.size();
            if (numKeysToBeAdded == 0)
                return;
    
            // 计算容量是否足够,
            // 若“当前实际容量 < 需要的容量”,则将容量x2。
            if (numKeysToBeAdded > threshold) {
                int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
                if (targetCapacity > MAXIMUM_CAPACITY)
                    targetCapacity = MAXIMUM_CAPACITY;
                int newCapacity = table.length;
                while (newCapacity < targetCapacity)
                    newCapacity <<= 1;
                if (newCapacity > table.length)
                    resize(newCapacity);
            }
    
            // 将“m”中的元素逐个添加到WeakHashMap中。
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
                put(e.getKey(), e.getValue());
        }
    
        // 删除“键为key”元素
        public V remove(Object key) {
            Object k = maskNull(key);
            // 获取哈希值。
            int h = HashMap.hash(k.hashCode());
            Entry[] tab = getTable();
            int i = indexFor(h, tab.length);
            Entry<K,V> prev = tab[i];
            Entry<K,V> e = prev;
    
            // 删除链表中“键为key”的元素
            // 本质是“删除单向链表中的节点”
            while (e != null) {
                Entry<K,V> next = e.next;
                if (h == e.hash && eq(k, e.get())) {
                    modCount++;
                    size--;
                    if (prev == e)
                        tab[i] = next;
                    else
                        prev.next = next;
                    return e.value;
                }
                prev = e;
                e = next;
            }
    
            return null;
        }
    
        // 删除“键值对”
        Entry<K,V> removeMapping(Object o) {
            if (!(o instanceof Map.Entry))
                return null;
            Entry[] tab = getTable();
            Map.Entry entry = (Map.Entry)o;
            Object k = maskNull(entry.getKey());
            int h = HashMap.hash(k.hashCode());
            int i = indexFor(h, tab.length);
            Entry<K,V> prev = tab[i];
            Entry<K,V> e = prev;
    
            // 删除链表中的“键值对e”
            // 本质是“删除单向链表中的节点”
            while (e != null) {
                Entry<K,V> next = e.next;
                if (h == e.hash && e.equals(entry)) {
                    modCount++;
                    size--;
                    if (prev == e)
                        tab[i] = next;
                    else
                        prev.next = next;
                    return e;
                }
                prev = e;
                e = next;
            }
    
            return null;
        }
    
        // 清空WeakHashMap,将所有的元素设为null
        public void clear() {
            while (queue.poll() != null)
                ;
    
            modCount++;
            Entry[] tab = table;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
            size = 0;
    
            while (queue.poll() != null)
                ;
        }
    
        // 是否包含“值为value”的元素
        public boolean containsValue(Object value) {
            // 若“value为null”,则调用containsNullValue()查找
            if (value==null)
                return containsNullValue();
    
            // 若“value不为null”,则查找WeakHashMap中是否有值为value的节点。
            Entry[] tab = getTable();
            for (int i = tab.length ; i-- > 0 ;)
                for (Entry e = tab[i] ; e != null ; e = e.next)
                    if (value.equals(e.value))
                        return true;
            return false;
        }
    
        // 是否包含null值
        private boolean containsNullValue() {
            Entry[] tab = getTable();
            for (int i = tab.length ; i-- > 0 ;)
                for (Entry e = tab[i] ; e != null ; e = e.next)
                    if (e.value==null)
                        return true;
            return false;
        }
    
        // Entry是单向链表。
        // 它是 “WeakHashMap链式存储法”对应的链表。
        // 它实现了Map.Entry 接口,即实现getKey(), getValue(), setValue(V value), equals(Object o), hashCode()这些函数
        private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
            private V value;
            private final int hash;
            // 指向下一个节点
            private Entry<K,V> next;
    
            // 构造函数。
            Entry(K key, V value,
              ReferenceQueue<K> queue,
                  int hash, Entry<K,V> next) {
                super(key, queue);
                this.value = value;
                this.hash  = hash;
                this.next  = next;
            }
    
            public K getKey() {
                return WeakHashMap.<K>unmaskNull(get());
            }
    
            public V getValue() {
                return value;
            }
    
            public V setValue(V newValue) {
            V oldValue = value;
                value = newValue;
                return oldValue;
            }
    
            // 判断两个Entry是否相等
            // 若两个Entry的“key”和“value”都相等,则返回true。
            // 否则,返回false
            public boolean equals(Object o) {
                if (!(o instanceof Map.Entry))
                    return false;
                Map.Entry e = (Map.Entry)o;
                Object k1 = getKey();
                Object k2 = e.getKey();
                if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                    Object v1 = getValue();
                    Object v2 = e.getValue();
                    if (v1 == v2 || (v1 != null && v1.equals(v2)))
                        return true;
                }
                return false;
            }
    
            // 实现hashCode()
            public int hashCode() {
                Object k = getKey();
                Object v = getValue();
                return  ((k==null ? 0 : k.hashCode()) ^
                         (v==null ? 0 : v.hashCode()));
            }
    
            public String toString() {
                return getKey() + "=" + getValue();
            }
        }
    
        // HashIterator是WeakHashMap迭代器的抽象出来的父类,实现了公共了函数。
        // 它包含“key迭代器(KeyIterator)”、“Value迭代器(ValueIterator)”和“Entry迭代器(EntryIterator)”3个子类。
        private abstract class HashIterator<T> implements Iterator<T> {
            // 当前索引
            int index;
            // 当前元素
            Entry<K,V> entry = null;
            // 上一次返回元素
            Entry<K,V> lastReturned = null;
            // expectedModCount用于实现fast-fail机制。
            int expectedModCount = modCount;
    
            // 下一个键(强引用)
            Object nextKey = null;
    
            // 当前键(强引用)
            Object currentKey = null;
    
            // 构造函数
            HashIterator() {
                index = (size() != 0 ? table.length : 0);
            }
    
            // 是否存在下一个元素
            public boolean hasNext() {
                Entry[] t = table;
    
                // 一个Entry就是一个单向链表
                // 若该Entry的下一个节点不为空,就将next指向下一个节点;
                // 否则,将next指向下一个链表(也是下一个Entry)的不为null的节点。
                while (nextKey == null) {
                    Entry<K,V> e = entry;
                    int i = index;
                    while (e == null && i > 0)
                        e = t[--i];
                    entry = e;
                    index = i;
                    if (e == null) {
                        currentKey = null;
                        return false;
                    }
                    nextKey = e.get(); // hold on to key in strong ref
                    if (nextKey == null)
                        entry = entry.next;
                }
                return true;
            }
    
            // 获取下一个元素
            protected Entry<K,V> nextEntry() {
                if (modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                if (nextKey == null && !hasNext())
                    throw new NoSuchElementException();
    
                lastReturned = entry;
                entry = entry.next;
                currentKey = nextKey;
                nextKey = null;
                return lastReturned;
            }
    
            // 删除当前元素
            public void remove() {
                if (lastReturned == null)
                    throw new IllegalStateException();
                if (modCount != expectedModCount)
                    throw new ConcurrentModificationException();
    
                WeakHashMap.this.remove(currentKey);
                expectedModCount = modCount;
                lastReturned = null;
                currentKey = null;
            }
    
        }
    
        // value的迭代器
        private class ValueIterator extends HashIterator<V> {
            public V next() {
                return nextEntry().value;
            }
        }
    
        // key的迭代器
        private class KeyIterator extends HashIterator<K> {
            public K next() {
                return nextEntry().getKey();
            }
        }
    
        // Entry的迭代器
        private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
            public Map.Entry<K,V> next() {
                return nextEntry();
            }
        }
    
        // WeakHashMap的Entry对应的集合
        private transient Set<Map.Entry<K,V>> entrySet = null;
    
        // 返回“key的集合”,实际上返回一个“KeySet对象”
        public Set<K> keySet() {
            Set<K> ks = keySet;
            return (ks != null ? ks : (keySet = new KeySet()));
        }
    
        // Key对应的集合
        // KeySet继承于AbstractSet,说明该集合中没有重复的Key。
        private class KeySet extends AbstractSet<K> {
            public Iterator<K> iterator() {
                return new KeyIterator();
            }
    
            public int size() {
                return WeakHashMap.this.size();
            }
    
            public boolean contains(Object o) {
                return containsKey(o);
            }
    
            public boolean remove(Object o) {
                if (containsKey(o)) {
                    WeakHashMap.this.remove(o);
                    return true;
                }
                else
                    return false;
            }
    
            public void clear() {
                WeakHashMap.this.clear();
            }
        }
    
        // 返回“value集合”,实际上返回的是一个Values对象
        public Collection<V> values() {
            Collection<V> vs = values;
            return (vs != null ?  vs : (values = new Values()));
        }
    
        // “value集合”
        // Values继承于AbstractCollection,不同于“KeySet继承于AbstractSet”,
        // Values中的元素能够重复。因为不同的key可以指向相同的value。
        private class Values extends AbstractCollection<V> {
            public Iterator<V> iterator() {
                return new ValueIterator();
            }
    
            public int size() {
                return WeakHashMap.this.size();
            }
    
            public boolean contains(Object o) {
                return containsValue(o);
            }
    
            public void clear() {
                WeakHashMap.this.clear();
            }
        }
    
        // 返回“WeakHashMap的Entry集合”
        // 它实际是返回一个EntrySet对象
        public Set<Map.Entry<K,V>> entrySet() {
            Set<Map.Entry<K,V>> es = entrySet;
            return es != null ? es : (entrySet = new EntrySet());
        }
    
        // EntrySet对应的集合
        // EntrySet继承于AbstractSet,说明该集合中没有重复的EntrySet。
        private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
            public Iterator<Map.Entry<K,V>> iterator() {
                return new EntryIterator();
            }
    
            // 是否包含“值(o)”
            public boolean contains(Object o) {
                if (!(o instanceof Map.Entry))
                    return false;
                Map.Entry e = (Map.Entry)o;
                Object k = e.getKey();
                Entry candidate = getEntry(e.getKey());
                return candidate != null && candidate.equals(e);
            }
    
            // 删除“值(o)”
            public boolean remove(Object o) {
                return removeMapping(o) != null;
            }
    
            // 返回WeakHashMap的大小
            public int size() {
                return WeakHashMap.this.size();
            }
    
            // 清空WeakHashMap
            public void clear() {
                WeakHashMap.this.clear();
            }
    
            // 拷贝函数。将WeakHashMap中的全部元素都拷贝到List中
            private List<Map.Entry<K,V>> deepCopy() {
                List<Map.Entry<K,V>> list = new ArrayList<Map.Entry<K,V>>(size());
                for (Map.Entry<K,V> e : this)
                    list.add(new AbstractMap.SimpleEntry<K,V>(e));
                return list;
            }
    
            // 返回Entry对应的Object[]数组
            public Object[] toArray() {
                return deepCopy().toArray();
            }
    
            // 返回Entry对应的T[]数组(T[]我们新建数组时,定义的数组类型)
            public <T> T[] toArray(T[] a) {
                return deepCopy().toArray(a);
            }
        }
    }
    

    因此,这里的引用处理并不是自动的,其实是我们在调用某些方法的时候处理,所以我们认为它不是一种自动的,只是表面上看起来是这种处理。
    具体的代码,将开始的map定义为一个WeakHashMap,最终的输出类似如下所示:

    9993回收了:java.lang.ref.WeakReference@12aa816
    9994回收了:java.lang.ref.WeakReference@2bd967
    9995回收了:java.lang.ref.WeakReference@13e9593
    weakHashMap.size->4
    

    在上面的代码中,由于weakhashmap不允许自定义queue,所以上面的监控是针对value的。在weakHashMap中,queue在weakhashmap在内部定义,并且由内部消化使用了。如果我们在自己进一步处理,那就只能自定义类似weakHashMap实现,或者使用反向操作。即在监控到变化之后,自己处理map的kv。

    队列监控的反向操作

    反向操作,即意味着一个数据变化了,可以通过weakReference对象反向拿相关的数据,从而进行业务的处理。比如,我们可以通过继承weakReference对象,加入自定义的字段值,额外处理。一个类似weakHashMap如下,这时,我们不再将key值作为弱引用处理,而是封装在weakReference对象中,以实现额外的处理。

    import java.lang.ref.ReferenceQueue;
    import java.lang.ref.WeakReference;
    
    //描述一种强key关系的处理,当value值被回收之后,我们可以通过反向引用将key从map中移除的做法
    //即通过在weakReference中加入其所引用的key值,以获取key信息,再反向移除map信息
    class WeakRef extends WeakReference<byte[]> {
       private Object key;
    
       WeakRef(Object key, byte[] referent, ReferenceQueue<? super byte[]> q) {
       	super(referent, q);
       	this.key = key;
       }
    
       public Object getKey() {
       	return key;
       }
    
       public void setKey(Object key) {
       	this.key = key;
       }
    }
    
    import java.lang.ref.ReferenceQueue;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Test {
    
       public static void main(String[] args) throws Exception {
       	final Map<Object, WeakRef> hashMap = new HashMap<>();
       	int _1M = 1024 * 1024;
       	ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
       	Thread thread = new Thread(() -> {
       		try {
       			int cnt = 0;
       			WeakRef k;
       			while ((k = (WeakRef) referenceQueue.remove()) != null) {
       				System.out.println((cnt++) + "回收了:" + k);
       				// 触发反向hash remove
       				hashMap.remove(k.getKey());
       				// 额外对key对象作其它处理,比如关闭流,通知操作等
       			}
       		} catch (InterruptedException e) {
       			// 结束循环
       		}
       	});
       	thread.setDaemon(true);
       	thread.start();
    
       	for (int i = 0; i < 10000; i++) {
       		String key = "mykey" + (i + 1);
       		byte[] bytesValue = new byte[_1M];
       		hashMap.put(key, new WeakRef(key, bytesValue, referenceQueue));
       	}
       	System.out.println("map.size->" + hashMap.size());
       }
    }
    

    其实就是拿到反向引用的key值(这里的value已经不存在了),因为kv映射已没有意义,将其从map中移除掉。同时,我们还可以作其它的操作。

    这个也可以理解为就是一个类似cache的实现。
    在cache中,key不重要并且通常都很少,value才是需要对待的。这里通过监控value变化,反向修改map,以达到控制kv的目的,避免出现无用的kv映射。

    相应的输出,如下所示:

    ...
    9988回收了:com.test1.WeakRef@a4377
    9989回收了:com.test1.WeakRef@18078a0
    9990回收了:com.test1.WeakRef@30c7e4
    9991回收了:com.test1.WeakRef@1480326
    9992回收了:com.test1.WeakRef@14bf343
    9993回收了:com.test1.WeakRef@112d632
    9994回收了:com.test1.WeakRef@1612513
    9995回收了:com.test1.WeakRef@a753aa
    9996回收了:com.test1.WeakRef@ec6f56
    9997回收了:com.test1.WeakRef@1009f3f
    map.size->2
    
  • 相关阅读:
    UNIX文件结构(转自UNIX/AIX操作系统基础教程) 分类: B3_LINUX 20121016 22:52 781人阅读 评论(0) 收藏
    umask 分类: B3_LINUX 20121014 16:34 296人阅读 评论(0) 收藏
    Linux 最常用命令 分类: B3_LINUX 20121013 11:23 663人阅读 评论(0) 收藏
    Linux标准目录配置(转自鸟哥) 分类: B3_LINUX 20121014 16:56 620人阅读 评论(0) 收藏
    完美图解教程 Linux环境VNC服务安装、配置与使用 分类: B3_LINUX 20121126 18:35 419人阅读 评论(0) 收藏
    c语言中<stdbool.h>的使用 分类: H_HISTORY 20130203 21:46 1416人阅读 评论(0) 收藏
    vi操作指令 分类: B3_LINUX 20121018 22:35 446人阅读 评论(0) 收藏
    使用sys无法通过sqlplus或者sqldeveloper连接数据库 分类: H2_ORACLE 20130204 14:02 600人阅读 评论(0) 收藏
    Oracle学习计划 分类: H2_ORACLE 20130204 14:04 393人阅读 评论(0) 收藏
    在AIX环境为Oracle表空间增加裸设备(逻辑卷) 分类: B3_LINUX 20121224 12:24 1043人阅读 评论(1) 收藏
  • 原文地址:https://www.cnblogs.com/gmhappy/p/11864003.html
Copyright © 2020-2023  润新知