WeakReference两个相关类WeakHashMap、ThreadLocal对比

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,只有主动去检查每个项是否失效。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容