ThreadLocal内存泄漏分析

2018-07-02  本文已影响12人  朽桜

今天看到ThreadLocal可能导致内存泄露的问题,之前并没有了解,于是从网上查找相关资料,现在总结一下:

几种引用的区别

弱引用对象的存在不会阻止它所指向的对象被垃圾回收器回收。假设垃圾收集器在某个时间点决定一个对象是弱可达的(weakly reachable)(也就是说当前指向它的全都是弱引用),这时垃圾收集器会清除所有指向该对象的弱引用,然后把这个弱可达对象标记为可终结(finalizable)的,这样它随后就会被回收。与此同时或稍后,垃圾收集器会把那些刚清除的弱引用放入创建弱引用对象时所指定的引用队列(Reference Queue)中。

源码分析

跟ThreadLocal相关的类有Thread和ThreadLocal的内部类ThreadLocalMap。
先看Thread的源码,Thread中持有一个ThreadLocalMap的引用。

    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

再来观察ThreadLocalMap

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

TheadLocalMap是真正存储对象的map,key是ThreadLocal对象。现在看一下平时使用最多的ThreadLocal的set()和get()方法:

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    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();
    }

getMap()方法:

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

其中的createMap()方法:

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

我们看到,get和set方法中,都是先获取当前线程,通过getMap方法获取到当前线程的threadLocalMap,来操作实际存储对象的这个map。另外注意一下,get方法中会调用getEntry方法,下文会用到。

原因分析

下面回到主题,为什么TheadLocal会导致内存泄露,先上一张图,实线是强引用,虚线代表弱引用:


1156565-20170724121152430-1111069410.png

ThreadLocalMap的key为ThreadLocal的弱引用,当没用对ThreadLocal的强引用时,上边我们也提到了,JVM进行GC时会回收ThreadLocal对象,导致ThreadLocalMap中的key为null,无妨访问到对应的value。同时Thread中一直持有ThreadLocalMap的引用,导致value无法被回收,如果该线程存活时间很长,就产生了内存泄露。
另外,ThreadLocalMap中getEntry()方法会对key为null的情况做单独处理:

        private Entry getEntry(ThreadLocal<?> key) {
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            if (e != null && e.get() == key)
                return e;
            else //查找不到 
                return getEntryAfterMiss(key, i, e);
        }

        private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
            Entry[] tab = table;
            int len = tab.length;

            while (e != null) {
                ThreadLocal<?> k = e.get();
                if (k == key) //找到直接返回
                    return e;
                if (k == null) //key为null 清理对应的value
                    expungeStaleEntry(i);
                else
                    i = nextIndex(i, len);
                e = tab[i];
            }
            return null;
        }

       private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

所以,ThreadLocalMap调用getEntry方式时,都会通过expungeStaleEntry方法移除key为null的entry和entry的value。
为什么要使用弱引用,通过弱引用,ThreadLocalMap虽然持有ThreadLocal的引用,但是并不会对JVM垃圾回收产生影响。另外上文我们也提到了,我们调用ThreadLocal的get方法时,会调用getEntry,这样就可以释放ThreadLocal为null的那些entry,避免了内存泄露。

结果

综合上面的分析,我们可以理解ThreadLocal内存泄漏的前因后果,那么怎么避免内存泄漏呢?
每次使用完ThreadLocal,都调用它的remove()方法,清除数据。

参考:
https://www.cnblogs.com/theo/p/6443493.html
http://www.importnew.com/21206.html
http://blog.xiaohansong.com/2016/08/06/ThreadLocal-memory-leak/
https://www.ezlippi.com/blog/2017/12/threadlocal.html

上一篇下一篇

猜你喜欢

热点阅读