ThreadLocal原理分析与内存泄漏的原因

前言:

ThreadLocal的原理是每个线程保存ThreadLocal.ThreadLocalMap。实现线程独享变量副本保证线程安全。

1. Thread源码分析,ThreadLocal.ThreadLocalMap是Thread的成员变量

public
class Thread implements Runnable {
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    //当前线程的传递
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    //子线程传递
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

ThreadLocal的原理

2. 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) {
            //this的作用是获取当前ThreadLocal变量所要实现线程安全的值,仅当多个ThreadLocal的时候起作用(此处是我的推断,有问题请指出)
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

其中getMap方法

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

意思是获取线程的ThreadLocal.ThreadLocalMap,获取变量值;

再看setInitialValue();如果没有当前threadlocal为key的值,则initialValue方法默认初始化null。

/**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

3. set方法

this的作用是获取当前ThreadLocal变量所要实现线程安全的值,仅当多个ThreadLocal的时候起作用(此处是我的推断,有问题请指出)

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

获取当前线程,getMap(),set变量值。没有map则createMap

 当前线程new一个,很简单。

/**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

4. 内存泄漏的原因主要有两个方面

4.1 弱引用

    /**
     * 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 not
     * used, stale entries are guaranteed to be removed only when
     * the table starts running out of space.
     */
    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> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal k, Object v) {
                //key,是弱引用
                super(k);
                value = v;
            }
        }

ThreadLocalMap 的存储Entry的key是弱引用类型

4.2 TreadLocal,就是上文提到的作为key的this。

TreadLocal对象使用完成或者内存不足时,ThreadLocalMap的Entry的key会GC,

但是ThreadLocalMap 的value强引用还在,在GC Root(栈帧本地变量表)的时候,不会GC。

5. 总结

如果线程一直运行,当一直使用ThreadLocal的时候,由于Entry的key是弱引用,value是强引用。

如果value一直使用,那么引用一直存在。就会出现一个null为key的value的map;

仅当线程对象GC的时候ThreadLocalMap 才会GC回收,如果线程长期运行,就会一直出现多个key为null的Entry。这些不会再使用key为null的Entry就存在内存泄漏的风险。

6. 解决方法

ThreadLocal使用完毕,手工调用ThreadLocal对象的remove()方法;当然set与get方法都会检查当前线程的threadlocal副本是否为null。只是如果我们长期没用这个thread local对象,就需要手动remove,回收内存。

    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();
                    //清除null的key
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

进一步跟踪

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();
                //key为null,entry置为null
                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;
        }

如果key为null,Entry就会置为null。

你可能感兴趣的:(Java,并发编程)