ThreadLocal 内存泄漏

ThreadLocal 翻译就是线程局部变量,就是这个变量只存在于当前的线程,只存在于当前的线程,那么完美解决了并发共享资源导致并发不安全的问题。

源码

java.lang.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); // 1
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this); 
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
   
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

// 1 从当前线程获取一个ThreadLocalMap,threadLocals 是Thread中的一个变量,ThreadLocalMap是Thread中的一个静态内部类。

Thread 类中的变量 threadLocals

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

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

        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

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

        /**
         * The number of entries in the table.
         */
        private int size = 0;

ThreadLocalMap的Entry 类 注释中说道当entry.get() == null 代表key不再被引用,这个entry可以从table中释放了,也可以看到Entry.java继承了WeakReference.java(弱引用)

看到Entry[]table 变量 和Entry类,可以理出来 引用关系为 Thread->ThreadLocalMap-> Entry[]->Entry-> ThreadLocal 和 Value。

引用关系

引用概念

强引用

强引用是使用最普遍的引用。如果一个对象具有强引用,那垃圾回收器绝不会回收它。

软引用

如果一个对象只具有软引用,则内存空间充足时,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。

弱引用

弱引用也是用来描述那些非必须对象,但是它的强度比软引用更弱一些,被弱引用关联的对象只能生存到下一次垃圾收集发生为止。当垃圾收集器开始工作,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。在JDK 1.2版之后提供了WeakReference类来实现弱引用。

  public static void main(String[] args) {
        WeakReferenceObject weakReferenceObject = new WeakReferenceObject();
        WeakReference<WeakReferenceObject> weakReference = new WeakReference<>(weakReferenceObject);
        System.out.println(weakReference.get());
        System.gc();
        System.out.println(weakReference.get());
        weakReferenceObject = null;
        System.gc();
        System.out.println(weakReference.get());
    }

    public static class WeakReferenceObject{
        @Override
        protected void finalize() throws Throwable {
            System.out.println("finalize ");
        }
    }
// output
WeakReferenceDemo$WeakReferenceObject@4d591d15
com.daxiyan.study.base.concurrent.WeakReferenceDemo$WeakReferenceObject@4d591d15
null
finalize 

虚引用

虚引用顾名思义,就是形同虚设。与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收。

ThreadLocal的弱引用

// Entry的构造方法中可以看出ThreadLocal 作为WeakReference的referent。那么在下一次垃圾回收时Entry中的ThreadLocal会被回收掉。

内存泄漏

这里的内存泄漏指的是 无用对象(不再使用的对象)持续占有内存或无用对象的内存得不到及时释放,从而造成内存空间的浪费称为内存泄漏。

当ThreadLocal变量和 Entry的Key ThreadLocal 弱引用被释放后,但是Entry的value还没被释放,并且不再使用,这时就导致了内存泄漏。

内存泄漏

ThreadLocal对Entry的key为null情况的优化

java.lang.ThreadLocal.ThreadLocalMap#getEntry

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

如果当前ThreadLocal匹配不到key,那么将调用getEntryAfterMiss方法。

java.lang.ThreadLocal.ThreadLocalMap#getEntryAfterMiss

 /**
         * Version of getEntry method for use when key is not found in
         * its direct hash slot.
         *
         * @param  key the thread local object
         * @param  i the table index for key's hash code
         * @param  e the entry at table[i]
         * @return the entry associated with key, or null if no such
         */
        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)  // 1 key为null,释放Entry。
                    expungeStaleEntry(i);
                else
                    i = nextIndex(i, len);
                e = tab[i];
            }
            return null;
        }

// 1 key为null,释放Entry。

java.lang.ThreadLocal.ThreadLocalMap#expungeStaleEntry

 /**
         * Expunge a stale entry by rehashing any possibly colliding entries
         * lying between staleSlot and the next null slot.  This also expunges
         * any other stale entries encountered before the trailing null.  See
         * Knuth, Section 6.4
         *
         * @param staleSlot index of slot known to have null key
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         */
        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;
        }

可以看到当调用get方法会触发key为null的Entry释放

内存泄漏的Demo

当threadLocal对象设为null时,value再也无法获取到,发生了内存泄漏,使用线程池确保线程不销毁,同时保证该线程不再被调用ThreadLocal.get,ThreadLocal.set方法,因为这两个方法中都存在 清除key为null 的Entry。

环境:java1.8
虚拟机启动参数:-Xms64M -Xmx64M

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalMemoryLeak {

    private static ExecutorService executorService = Executors.newFixedThreadPool(100);

    public static void main(String[] args) throws InterruptedException, NoSuchFieldException, IllegalAccessException {

        for (int i = 0; i <80 ; i++) {
            // 等待垃圾回收执行
            Thread.sleep(100);

            ThreadLocal<ByteObject> threadLocal = new ThreadLocal<ByteObject>(){
                @Override
                protected ByteObject initialValue() {
                    return new ByteObject();
                }
            };
            executorService.execute(()->{
                threadLocal.get();
                // 不remove将导致内存溢出
                //threadLocal.remove();
            });

        }
        Thread.sleep(3000);
        executorService.shutdown();
    }

    public static class ByteObject{
        // 5MB
        private byte [] bytes = new byte[5*1024*1024];

        @Override
        protected void finalize() throws Throwable {
            System.out.println(" finalize");
        }
    }
}


注释掉remove代码,控制台会打印java.lang.OutOfMemoryError: Java heap space。

threadLocal初始化代码 放在for循环里,for循环后不再被引用,在垃圾回收的时候将释放内存。因为线程词核心线程数100 大于需要的线程数80,不会触发在同一个线程调用get方法,所以导致ByteObject不会被释放而内存溢出。

如果将核心线程池改为1,此时无需remove,也不会存在内存溢出的情况,因为重复调用同一个线程的get方法,所以也会触发回收ByteObject。

在for循环开始初我sleep 100 毫秒,让垃圾回收有时间进行,否则,即使不注释掉remove也会导致内存溢出。

使用IDEA的visualgc插件观察

有remove操作

可以看到老年代一直保持在16M,内存没有泄露,所以没有内存溢出。

没有remove操作

可以看到老年代一直保持在41M,由于内存泄漏,老年代一直释放不了,导致了内存溢出。

总结

使用ThreadLocal的完成后,要及时调用remove方法。

参考资料

ThreadLocal (Java Platform SE 8 )
关于Java中的WeakReference
ThreadLocal源码解读

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355

推荐阅读更多精彩内容