ThreadLocal内存泄漏原因详解

ThreadLocal内存泄漏主要因弱引用的ThreadLocal对象被回收后,Entry仍由Thread强引用导致。当线程长期存在,如在线程池中,Entry不会被立即回收,引发内存问题。解决方法是及时调用ThreadLocal的remove方法。
摘要由CSDN通过智能技术生成

ThreadLocal的get方法

ThreadLocal的get方法操作步骤如下所示,可以看到其实最终是从当前线程的threadLocals里取出的,取的时候,调用的是getEntry方法,参数是ThreadLocal对象本身

  • ThreadLocal#get
    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
    
        /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
    


Thread#threadLocals结构

ThreadLocal本身并不存储对象,对象是存储在线程Thread内部的threadLocals属性上的

threadLocals属性的定义如下所示:


/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

ThreadLocal$ThreadLocalMap的结构如下

可以看出其实threadLocals是ThreadLocal的内部类ThreadLocalMap

  /**
     * ThreadLocalMap is a customized hash map suitable only for
     * maintaining thread local values. No operations are exported
     * outside of the ThreadLocal class. The class is package private to
     * allow declaration of fields in class Thread.  To help deal with
     * very large and long-lived usages, the hash table entries use
     * WeakReferences for keys. However, since reference queues are n
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值