011_java.util.WeakHashMap

继承体系

image.png
WeakHashMap 继承于AbstractMap,实现了Map接口。和Hashmap相比没有实现Clone和Serializable接口,因此既不具有克隆和序列化的特性

底层存储结构上,类似于HashMap,底层同样适用散列表进行存储。而这个类时不时就会被清理,因此原则上是不会让这个类放大量键值对的,因此结构只使用 桶+列表 的结构进行存储。

WeakHashMap内部的key是WeakReference类型的,当jvm gc的时候,如果这些key没有强引用存在的话,会被gc回收掉。当key被回收之后,会存储到ReferenceQueue队列。每次进行操作weakHashMap的时候都会进行同步处理,table中保存了全部的键值对,而queue中保存被GC回收的键值对;同步它们,就是删除table中被GC回收的键值对。

这里我们跑一下测试例子,看看效果:

import java.util.Map;
import java.util.WeakHashMap;

public class WeakHashMapTest {

public static void main(String[] args) {
        Map<String, Integer> map = new WeakHashMap<>(3);
        
        String str3 = new String("3");
        
        // 放入2个new String()声明的字符串
        map.put(new String("1"), 1);
        map.put(new String("2"), 2);
        // 放入强引用3
        map.put(str3, 3);
        // 放入直接声明量
        map.put("6", 6);
        
        // gc前输出 : {6=6, 1=1, 2=2, 3=3}
        System.out.println(map);
        
        // gc一下
        System.gc();
        
        // gc后输出 :{6=6, 3=3}
        System.out.println(map);
    }
}

在这里通过new String()声明的变量没有强引用,使用"6"这种声明方式会一直存在于常量池中,不会被清理,所以"6"这个元素会一直在map里面,“2”与“3”会随着gc都会被清理掉。

重要属性

/**
 * 默认初始容量为16
 */
private static final int DEFAULT_INITIAL_CAPACITY = 16;

/**
 * 最大容量为2的30次方
 */
private static final int MAXIMUM_CAPACITY = 1 << 30;

/**
 * 默认装载因子
 */
private static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
 * 桶
 */
Entry<K,V>[] table;

/**
 * 元素个数
 */
private int size;

/**
 * 扩容门槛,等于capacity * loadFactor
 */
private int threshold;

/**
 * 装载因子
 */
private final float loadFactor;

/**
 * 引用队列,当弱键失效的时候会把Entry添加到这个队列中
 */
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();

Entry内部类

Entry是存储数据的,其内包含K-V数据,但是WeakHashMap继承WeakReference类,key的存储委托给这个父类了。如下,在Entry的构造函数内将调用super方法将key传入。


// 本身变为一个WeakReference
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
    // 没有key, 因为key是作为弱引用存到Referen类中
    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) {
        // 调用WeakReference的构造方法初始化key和引用队列
        super(key, queue);
        this.value = value;
        this.hash  = hash;
        this.next  = next;
    }

    @SuppressWarnings("unchecked")
    public K getKey() {
        return (K) WeakHashMap.unmaskNull(get());
    }

    public V getValue() {
        return value;
    }

    public V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public boolean equals(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry<?,?> e = (Map.Entry<?,?>)o;
        K k1 = getKey();
        Object k2 = e.getKey();
        if (k1 == k2 || (k1 != null && k1.equals(k2))) {
            V v1 = getValue();
            Object v2 = e.getValue();
            if (v1 == v2 || (v1 != null && v1.equals(v2)))
                return true;
        }
        return false;
    }

    public int hashCode() {
        K k = getKey();
        V v = getValue();
        return Objects.hashCode(k) ^ Objects.hashCode(v);
    }

    public String toString() {
        return getKey() + "=" + getValue();
    }
}

而这里的WeakReference类可以把某个Object包裹,并注册到某个ReferenceQueue(或者不注册)

public class WeakReference<T> extends Reference<T> {

    public WeakReference(T referent) {
        super(referent);
    }

    public WeakReference(T referent, ReferenceQueue<? super T> q) {
        super(referent, q);
    }

}

public abstract class Reference<T> {
    // 实际存储key的地方
    private T referent;         /* Treated specially by GC */
    // 引用队列
    volatile ReferenceQueue<? super T> queue;
    
    Reference(T referent, ReferenceQueue<? super T> queue) {
        this.referent = referent;
        this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
    }
    ...
    public boolean enqueue() {
        return this.queue.enqueue(this);
    }
    ...
}

这里需要注意其入队方法,可以看到是将this进行入队,也就是当发生GC的时候key会被回收,而进入到回收队列的是Entry对象。

构造函数

WeakHashMap的构造函数与Hashmap的构造函数大体上一样,操作也一样,在这里不过多描述

public WeakHashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Initial Capacity: "+
                initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;

    if (loadFactor <= 0 || Float.isN2aN(loadFactor))
        throw new IllegalArgumentException("Illegal Load factor: "+
                loadFactor);
    int capacity = 1;
    while (capacity < initialCapacity)
        capacity <<= 1;
    // 根据容量创造table
    table = newTable(capacity);
    this.loadFactor = loadFactor;
    // 得到扩容门槛
    threshold = (int)(capacity * loadFactor);
}

public WeakHashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public WeakHashMap() {
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

public WeakHashMap(Map<? extends K, ? extends V> m) {
    this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
            DEFAULT_INITIAL_CAPACITY),
            DEFAULT_LOAD_FACTOR);
    putAll(m);
}

重要方法

put方法

put方法帮助我们将键值对放入WeakHashMap,期间会对无效Entry进行清理

public V put(K key, V value) {
    // 如果是null则返回一个Object
    Object k = maskNull(key);
    // 得到这个key的hash值
    int h = hash(k);
    // 得到当前的桶,这个时候会进行剔除无效Entry
    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;
}

private static final Object NULL_KEY = new Object();

private static Object maskNull(Object key) {
    return (key == null) ? NULL_KEY : key;
}

getTable()方法

从上面的方法中提到同步问题,所谓同步指的就是把在ReferenceQueue中的object在WeakHashMap删去

private Entry<K,V>[] getTable() {
    expungeStaleEntries();
    return table;
}

private void expungeStaleEntries() {
    // 遍历引用队列,注意x是Entry对象
    for (Object x; (x = queue.poll()) != null; ) {
          // 拿到Object之后才进行锁住队列操作
      		synchronized (queue) {
            @SuppressWarnings("unchecked")
            Entry<K,V> e = (Entry<K,V>) x;
            int i = indexFor(e.hash, 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;
                    // Must not null out e.next;
                    // stale entries may be in use by a HashIterator
                    e.value = null; // Help GC
                    size--;
                    break;
                }
                prev = p;
                p = next;
            }
        }
    }
}

resize方法

put方法会涉及到扩容逻辑,这里的逻辑是新建一个扩容后的桶,然后进行迁移。这里需要注意的事情是,当在产生新桶并迁移的过程中将会对key是null的Entry进行清理,有可能导致旧桶的容量已经足够了,那就将新桶数据再迁移回旧桶。

void resize(int newCapacity) {
    // 获取旧桶,getTable()的时候会剔除失效的Entry
    Entry<K,V>[] oldTable = getTable();
    // 旧容量
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }

    // 新桶
    Entry<K,V>[] newTable = newTable(newCapacity);
    // 把元素从旧桶转移到新桶
    transfer(oldTable, newTable);
    // 把新桶赋值桶变量
    table = newTable;

    // 如果元素个数大于扩容门槛的一半,则使用新桶和新容量,并计算新的扩容门槛
    if (size >= threshold / 2) {
        threshold = (int)(newCapacity * loadFactor);
    } else {
        // 否则把元素再转移回旧桶,还是使用旧桶
        // 因为在transfer的时候会清除失效的Entry,所以元素个数可能没有那么大了,就不需要扩容了
        expungeStaleEntries();
        transfer(newTable, oldTable);
        table = oldTable;
    }
}

private void transfer(Entry<K,V>[] src, Entry<K,V>[] 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();
            // 如果key等于了null就清除,说明key被gc清理掉了,则把整个Entry清除
            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;
        }
    }
}

(1)判断旧容量是否达到最大容量;

(2)新建新桶并把元素全部转移到新桶中;

(3)如果转移后元素个数不到扩容门槛的一半,则把元素再转移回旧桶,继续使用旧桶,说明不需要扩容;

(4)否则使用新桶,并计算新的扩容门槛;

(5)转移元素的过程中会把key为null的元素清除掉,所以size会变小;

get方法

public V get(Object key) {
    Object k = maskNull(key);
    // 计算hash
    int h = hash(k);
    Entry<K,V>[] tab = getTable();
    int index = indexFor(h, tab.length);
    Entry<K,V> e = tab[index];
    // 遍历链表,找到了就返回
    while (e != null) {
        if (e.hash == h && eq(k, e.get()))
            return e.value;
        e = e.next;
    }
    return null;
}

remove方法

public V remove(Object key) {
    Object k = maskNull(key);
    // 计算hash
    int h = hash(k);
    Entry<K,V>[] tab = getTable();
    int i = indexFor(h, tab.length);
    // 元素所在的桶的第一个元素
    Entry<K,V> prev = tab[i];
    Entry<K,V> e = prev;

    // 遍历链表
    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;
}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值