ThreadLocal原理与内存泄漏问题

Java中的引用类型:强软弱虚
1)强引用:我们平时用到的引用 Object o = new Object();
2)软引用:是一个由SoftReference定义的数据,当强引用对象所需内存不足的时候,GC会回收掉软引用对象。
软引用非常适合做缓存。

//new byte[1024 * 1024 * 10]这个是软引用
SoftReference m = new SoftReference<>(new byte[1024 * 1024 * 10]);
软引用示例

3)弱引用:是一个由WeakReference定义的数据,只要GC就会回收

WeakReference m_weak = new WeakReference<>(new Tl());

4)虚引用:

PhantomReference m_ph = new PhantomReference<>(new Tl(), new ReferenceQueue<>());
//作用:防止堆外内存泄漏。没太懂
ThreadLocal:线程本地管理

在当前线程取值,也只有当前线程可以取值

每个线程都有一个ThreadLocalMap类型的threadLocals,这个ThreadLocalMap结构类似
HashMap的结构,里面有个table数据结构,table里面存放的是Entry/Node节点。通过ThreadLocal.set()将当前ThreadLocal放到当前线程的threadLocals中去

class Thread {
    ... 
    ThreadLocal.ThreadLocalMap threadLocals = null;
    ...
}
ThreadLocal tl = new ThreadLocal<>();
        tl.set(new Object());


public void set(T value) {
        Thread t = Thread.currentThread();//获取当前线程
        ThreadLocalMap map = getMap(t);//获取当前线程的threadLocals
        if (map != null)
            map.set(this, value);//将当前ThreadLocal和value通过键值对形式放到threadLocals
        else
            createMap(t, value);
    }

/**
 * ThreadLocalMap.set方法
*/
 private void set(ThreadLocal key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            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)]) {
                ThreadLocal k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
 
 

ThreadLocalMap.set方法,就是将key(ThreadLocal对象)与value(业务对象)封装成
Entry节点然后放到table中去。注意:new Entry()里面的代码,涉及到了内存泄漏的设计,如下:

static class Entry extends WeakReference> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal k, Object v) {
                super(k);
                value = v;
            }
        }

注意,Entry继承了WeakReference弱引用,通过super(k),将k(ThreadLocal对象)放到
用弱引用指向。这样,当前线程中,k被两个地方引用:1、定义ThreadLocal的引用 tl
2、Entry中的弱引用k。当tl = null之后,ThreadLocal还剩下k这一个弱引用,下次垃圾回收的时候就会将
它回收掉,从而不会造成内存泄漏;但是GC掉弱引用对象后,value还存在,所以正确的用法是:

ThreadLocal tl = new ThreadLocal<>();
tl.set(new Object());
tl.remove(); //Remove the entry for key.
 
 

待续...

你可能感兴趣的:(ThreadLocal原理与内存泄漏问题)