1.Entry对比
WeakHashMap的Entry带queue,ThreadLocal的Entry不带queue。
1.1 WeakHashMap的Entry
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) {
super(key, queue);
this.value = value;
this.hash = hash;
this.next = next;
}
1.2 存储在ThreadLocalMap中的Entry
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
2.差别
- 在WeakHashMap中expungeStaleEntries方法会根据ReferenceQueue queue剔除失效的Entry,在getTable size resize时会调用,这些方法会被几乎所有方法调用
- 在ThreadLocal中当Entry的key就变为了null,会在get set remove操作进行进行检查并清除失效的项。
WeakHashMap可以根据queue直接处理失效的项,而ThreadLocal不带queue,只有主动去检查每个项是否失效。