基础数据机构之WeakHashMap源码分析

来源:互联网 发布:万德数据库电话 编辑:程序博客网 时间:2024/06/05 04:23

1.WeakHashMap 在HashMap实现上,在HashMap上增加Entry的SoftReference软引用功能

 

源码分析

  Entry实体类继承WeakReference

 /**     * The entries in this hash table extend WeakReference, using its main ref     * field as the key.     */    private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {//继承WeakReference弱引用        private V value;        private final int hash;        private Entry<K,V> next;        /**         * Creates new entry.         */        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());//get()方法,获取该key的时候,判断是否被回收掉,如果被回收掉返回null        }
}


插入数据方式和HashMap插入数据方法一致,只是多了对WeakReference的null判断逻辑

 /**     * Associates the specified value with the specified key in this map.     * If the map previously contained a mapping for this key, the old     * value is replaced.     *     * @param key key with which the specified value is to be associated.     * @param value value to be associated with the specified key.     * @return the previous value associated with <tt>key</tt>, or     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.     *         (A <tt>null</tt> return can also indicate that the map     *         previously associated <tt>null</tt> with <tt>key</tt>.)     */    public V put(K key, V value) {        K k = (K) maskNull(key);//如果该key为null,那么直接使用NULL_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) {            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,V>(k, value, queue, h, e);        if (++size >= threshold)            resize(tab.length * 2);        return null;    }