一、类继承关系
二、概述
WeakHashMap是基于基于弱引用key和哈希表的Map接口实现类,通常用于实现对内存敏感的本地缓存。使用WeakHashMap时要求key不能被其他常驻内存的实例(如WeakHashMap中的value)引用,如果必须引用,则将引用方包装成WeakReference,如:m.put(key, new WeakReference(value))。当只有WeakHashMap实例保留了对目标key的引用时,下一次垃圾回收可能将该key从内存中删除掉,注意key删除了但是key对应的WeakReference实例还在WeakHashMap中。如果被删除了,则下一次调用WeakHashMap的某个方法时,WeakHashMap会首先将被垃圾回收掉的key对应的WeakReference实例及其value从WeakHashMap中删除。使用WeakHashMap时需要程序做好某个key突然没有的应对措施,key的删除是垃圾回收器决定的,对应用程序是不可控不可预知的。参考如下用例:
@Test
public void test() throws Exception {
ReferenceQueue queue = new ReferenceQueue();
WeakReference reference = new WeakReference(new Object(), queue);
System.out.println(reference);
System.gc();
Reference reference1 = queue.remove();
System.out.println(reference1);
System.out.println(reference1.get());//为null
}
@Test
public void test2() throws Exception {
Map<User,String> map=new WeakHashMap<>();
map.put(new User("shl",12),"shl");
map.put(new User("shl2",12),"shl2");
System.out.println(map.size());
//调用gc()方法时不保证垃圾回收器一直执行垃圾回收
System.gc();
System.gc();
System.gc();
System.out.println(map.size());
}
三、源码实现
1、全局变量定义
/**
* 默认初始容量
*/
private static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* 最大容量
*/
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 * load factor).
*/
private int threshold;
/**
* 负载因子
*/
private final float loadFactor;
/**
* 保存弱引用的队列,当垃圾回收器回收了某个弱引用对应的对象时,会将该弱引用放入队列中
*/
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
/**
* 代表为null的key
*/
private static final Object NULL_KEY = new Object();
/**
* 记录修改次数
*/
int modCount;
2、构造方法
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.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load factor: "+
loadFactor);
int capacity = 1;
//计算大于initialCapacity的最小的2的整数次方,跟HashMap中的实现相比,运算的次数更多
while (capacity < initialCapacity)
capacity <<= 1;
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);
}
3、存储key/value的数据结构
/**
* Entry继承自WeakReference
*/
private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> {
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) {
//此处自动将key包装成WeakReference
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
}
//此处获取key是从WeakReference中获取key的
@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();
}
}
4、公用方法
@SuppressWarnings("unchecked")
//返回指定容量的哈希表
private Entry<K,V>[] newTable(int n) {
return (Entry<K,V>[]) new Entry<?,?>[n];
}
/**
* 插入时对key做预处理,如果key为null转换为NULL_KEY
*/
private static Object maskNull(Object key) {
return (key == null) ? NULL_KEY : key;
}
/**
* 返回key时对key做预处理,如果key为NULL_KEY转换为null
*/
static Object unmaskNull(Object key) {
return (key == NULL_KEY) ? null : key;
}
/**
* 判断两个对象是否相等
*/
private static boolean eq(Object x, Object y) {
return x == y || x.equals(y);
}
/**
* 让低位字节参与运算,减少hash碰撞,相比HashMap运算次数更多
*/
final int hash(Object k) {
int h = k.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* 返回哈希表中索引
*/
private static int indexFor(int h, int length) {
return h & (length-1);
}
/**
* 从哈希表中删除弱引用队列保存的元素,弱引用队列中保存的元素是已经被垃圾回收器给回收的元素
* 注意Entry是继承自WeakReference对象,此时从引用队列获取的Entry实例中保存的key已经被垃圾回收器会回收了
*/
private void expungeStaleEntries() {
//不断的从弱引用队列中拉取元素
for (Object x; (x = queue.poll()) != null; ) {
synchronized (queue) {
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>) x;
//找到被删除元素所属的哈希索引
int i = indexFor(e.hash, table.length);
//获取该索引下哈希桶的头元素
//prev表示前一个元素
Entry<K,V> prev = table[i];
//p表示当前遍历的元素
Entry<K,V> p = prev;
//遍历哈希桶的单向链表
while (p != null) {
Entry<K,V> next = p.next;
//找到目标元素
if (p == e) {
//p和prev只有在都指向头元素时才相等,即待删除元素是头元素,将下一个元素置为头元素
if (prev == e)
table[i] = next;
else
//如果不是头元素,将前一个元素和下一个元素关联起来
prev.next = next;
//e.key已经为null,将value进一步置为null,从而被垃圾回收器回收
e.value = null;
//元素被移除,size减1,跳出循环
size--;
break;
}
//没找到key,pre置成当前元素,p置成下一个元素,继续遍历
prev = p;
p = next;
}
}
}
}
private Entry<K,V>[] getTable() {
expungeStaleEntries();
return table;
}
5、元素插入
public V put(K key, V value) {
Object k = maskNull(key);
int h = hash(k);
//getTable方法会自动清除被垃圾回收掉的元素
Entry<K,V>[] tab = getTable();
//找到该元素所属的hash桶
int i = indexFor(h, tab.length);
//遍历哈希桶中的单向链表
for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
//存在key相同的,覆盖原值
if (h == e.hash && eq(k, e.get())) {
V oldValue = e.value;
if (value != oldValue)
e.value = value;
return oldValue;
}
}
//没有相同key的元素
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;
}
6、key/value查找
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
Entry<K,V> getEntry(Object key) {
Object k = maskNull(key);
int h = hash(k);
//清除被回收的元素
Entry<K,V>[] 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;
}
public boolean containsValue(Object value) {
if (value==null)
return containsNullValue();
Entry<K,V>[] tab = getTable();
//遍历每个哈希桶
for (int i = tab.length; i-- > 0;)
//遍历哈希桶中的单向链表
for (Entry<K,V> e = tab[i]; e != null; e = e.next)
if (value.equals(e.value))
return true;
return false;
}
7、扩容
void resize(int newCapacity) {
//清除已被回收元素
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;
/*
* 因为存在垃圾回收的情况,原来size是大于threshold的,transfer执行时会将被回收的元素删除掉,导致size有可能小于
* threshold的二分之一
*/
if (size >= threshold / 2) {
//size依然较大,更新threshold值
threshold = (int)(newCapacity * loadFactor);
} else {
//垃圾回收器回收了大部分元素,此时不需要扩容了,将newTable中的元素转移到oldTable中
//之前的transfer没有删除元素,此处的expungeStaleEntries方法会删除元素
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();
//因为WeakHashMap对null的key转换成常量了,当key为null时表示该元素被垃圾回收期回收掉了
if (key == null) {
//此处将该元素保存的引用都置成null,便于垃圾回收,注意此时没有将上一个元素对该元素的引用删除掉,即该元素实际还在Map中
e.next = null;
e.value = null;
size--;
} else {
//按照扩容后的哈希桶重新hash,重新建立单向链表
int i = indexFor(e.hash, dest.length);
e.next = dest[i];
dest[i] = e;
}
e = next;
}
}
}
8、元素删除
//与元素查找逻辑相同
public V remove(Object key) {
Object k = maskNull(key);
int h = hash(k);
//清除已被回收元素
Entry<K,V>[] tab = getTable();
//找到key所属的哈希桶
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;
//找到目标key
if (h == e.hash && eq(k, e.get())) {
modCount++;
size--;
if (prev == e)
//如果目标key是哈希桶的头元素,将头元素置成下一个元素
tab[i] = next;
else
//不是头元素,建立前一个元素和下一个元素的关联
prev.next = next;
//返回key原来的value
return e.value;
}
//没有找到目标key,继续往下遍历
prev = e;
e = next;
}
return null;
}
9、元素遍历,Iterator接口实现
//遍历逻辑跟HashMap基本一致,只是为了适应WeakHashMap增加了两个用于保存下一个元素key和当前元素key的强引用实例
private abstract class HashIterator<T> implements Iterator<T> {
private int index;
private Entry<K,V> entry;
private Entry<K,V> lastReturned;
private int expectedModCount = modCount;
/**
* 对下一个key的强引用实例,避免在遍历时被垃圾回收掉
*/
private Object nextKey;
/**
* 当前key的强引用实例,避免在遍历时被垃圾回收掉
*/
private Object currentKey;
HashIterator() {
index = isEmpty() ? 0 : table.length;
}
public boolean hasNext() {
Entry<K,V>[] t = table;
//nextKey未初始化或者执行了nextEntry方法
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;
}
//将当前元素的key赋值给一个强引用实例,避免被回收
nextKey = e.get(); // hold on to key in strong ref
//如果已经被回收了,则将当前元素置成下一个元素,下一次循环中执行nextKey = e.get(),然后跳出循环
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,触发下一次执行hasNext()方法时查找元素的逻辑
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;
}
}
private class ValueIterator extends HashIterator<V> {
public V next() {
return nextEntry().value;
}
}
private class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
private class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}