ThreadLocalMap 内部持有变量的属性是Entry[] table

/**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

根据注释, 类Entry 是继承了WeakReference 弱引用类,用ThreadLocal 对象作为key,并且这个key 是弱引用的入参,当此key 对象不在被外部引用时,就会被垃圾回收,但是value 并不会被回收,它并不是若引用,只有 调用set remove rehash 方法时,判断keynull 时,删除value

        /**
         * Remove the entry for key.
         */
        private void remove(ThreadLocal<?> key) {
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                if (e.get() == key) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

因此,在我们日常写代码时,在业务流程完成后,调用remove 方法清理内存对象。


Fox_Valentin
1 声望1 粉丝