为什么ThreadLocalMap的静态内部类Entry要继承WeakReference<ThreadLocal<?>>?

static class ThreadLocalMap {

        /**
         * 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;
            }
        }

ThreadLocalMap是ThreadLocal的静态内部类。 Entry是ThreadLocalMap的静态内部类。
Entry继承WeakReference<ThreadLocal<?>>的目的是什么?
当Thread对象执行完之后,被GC回收,它内部的ThreadLocalMap也会随之被回收吧

阅读 4.3k
1 个回答

如果线程没有结束,但引用 ThreadLocal 的对象被回收,ThreadLocalMap 如果持有 ThreadLocal 的强引用,那不是内存泄漏了?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题