1.概述:
JDK源码:
* This class provides thread-local variables. These variables differ from * their normal counterparts in that each thread that accesses one (via its * { get} or { set} method) has its own, independently initialized * copy of the variable. { ThreadLocal} instances are typically private * static fields in classes that wish to associate state with a thread (e.g., * a user ID or Transaction ID).
翻译:
概括:
ThreadLocal提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度。
故事说明
我出门需要先坐公交再做地铁,这里的坐公交和坐地铁就好比是同一个线程内的两个函数,我就是一个线程,我要完成这两个函数都需要同一个东西:公交卡(北京公交和地铁都使用公交卡),那么我为了不向这两个函数都传递公交卡这个变量(相当于不是一直带着公交卡上路),我可以这么做:将公交卡事先交给一个机构,当我需要刷卡的时候再向这个机构要公交卡(当然每次拿的都是同一张公交卡)。这样就能达到只要是我(同一个线程)需要公交卡,何时何地都能向这个机构要的目的。
有人要说了:你可以将公交卡设置为全局变量啊,这样不是也能何时何地都能取公交卡吗?但是如果有很多个人(很多个线程)呢?大家可不能都使用同一张公交卡吧(我们假设公交卡是实名认证的),这样不就乱套了嘛。现在明白了吧?这就是ThreadLocal设计的初衷:提供线程内部的局部变量,在本线程内随时随地可取,隔离其他线程。
ThreadLocal实现原理
假设:
每个ThreadLocal类创建一个Map,然后用线程的ID作为Map的key,实例对象作为Map的value,这样就能达到各个线程的值隔离的效果。 (早起版本jdk是此种设计)
get方法的流程是这样的:
首先获取当前线程
根据当前线程获取一个Map
如果获取的Map不为空,则在Map中以ThreadLocal的引用作为key来在Map中获取对应的value e,否则转到5
如果e不为null,则返回e.value,否则转到5
Map为空或者e为空,则通过
initialValue
函数获取初始值value,然后用ThreadLocal的引用和value作为firstKey和firstValue创建一个新的Map
然后需要注意的是
虽然ThreadLocalMap是ThreadLocal的静态内部类,但是每个Thread内部都有一个ThreadLocalMap的成员变量。
ThreadLocal.ThreadLocalMap threadLocals = null;
总结原理:每个Thread维护一个ThreadLocalMap映射表,这个映射表的key是ThreadLocal实例本身,value是真正需要存储的Object。
这样设计的优点:
这样设计之后每个Map的Entry数量变小了:之前是Thread的数量,现在是ThreadLocal的数量,能提高性能,据说性能的提升不是一点两点(没有亲测)
当Thread销毁之后对应的ThreadLocalMap也就随之销毁了,能减少内存使用量。
深入一点:
hreadLocalMap是使用ThreadLocal的弱引用作为Key的:
考虑问题:ThreadLocal内存泄露
1.认为会造成的理由如下:
ThreadLocalMap使用ThreadLocal的弱引用???作为key,如果一个ThreadLocal没有外部强引用引用他,那么系统gc的时候,这个ThreadLocal势必会被回收,这样一来,ThreadLocalMap中就会出现key为null的Entry,就没有办法访问这些key为null的Entry的value,如果当前线程再迟迟不结束的话,这些key为null的Entry的value就会一直存在一条强引用链: Thread Ref -> Thread -> ThreaLocalMap -> Entry -> value 永远无法回收,造成内存泄露。
结合JDK源码分析:
2.JDK考虑到了这样的问题,ThreadLocalMap的getEntry方法,可以避免内存泄露:
ThreadLocalMap 的getEntry
函数的流程:
首先从ThreadLocal的直接索引位置(通过ThreadLocal.threadLocalHashCode & (len-1)运算得到)获取Entry e,如果e不为null并且key相同则返回e;
如果e为null或者key不一致则向下一个位置查询,如果下一个位置的key和当前需要查询的key相等,则返回对应的Entry,否则,如果key值为null,则擦除该位置的Entry,否则继续向下一个位置查询
在这个过程中遇到的key为null的Entry都会被擦除,那么Entry内的value也就没有强引用链,自然会被回收。仔细研究代码可以发现,set
操作也有类似的思想,将key为null的这些Entry都删除,防止内存泄露。但是光这样还是不够的,上面的设计思路依赖一个前提条件:要调用ThreadLocalMap的getEntry函数或者set函数。这当然是不可能任何情况都成立的,所以很多情况下需要使用者手动调用ThreadLocal的remove
函数,手动删除不再需要的ThreadLocal,防止内存泄露。所以JDK建议将ThreadLocal变量定义成private static
的,这样的话ThreadLocal的生命周期就更长,由于一直存在ThreadLocal的强引用,所以ThreadLocal也就不会被回收,也就能保证任何时候都能根据ThreadLocal的弱引用访问到Entry的value值,然后remove它,防止内存泄露。
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) 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; }
3.ThreadLocalMap 中的Entry的键ThreadLocal是weekReference,即弱引用。
在JVM垃圾回收是弱引用都会被GC回收。因此极易发生在某次GC后,某个线程的某个ThreadLocal变量变成null,那么在Entry中,key也变成null,在查找时就永远找不到,这个Entry的value就永远不会被用到,这就会导致内存泄露。
3.1解决:在ThreadLocalMap set方法时,添加了一段代码
if (k == null) {replaceStaleEntry(key, value, i); return;}
在选择数组的插入位置,当发现key为null时,会调用replaceStaleEntry,即把key=null的Entry移除,当然一般情况吧ThreadLocal声明成static final,这样可以保持ThreadLocal强引用。
4注意点:
为什么不转变成全局变量,因为这样还是共享了同一个变量,没有解决变量共享代理的并发问题。ThreadLocal中存储的应该是变量的拷贝或者重新new出来的对象,这样才算是副本。
ThreadLocal类中的几个主要的方法
/** * 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() { 159 Thread t = Thread.currentThread();//获取当前线程 ThreadLocalMap map = getMap(t);//获取当前线程对应的ThreadLocalMap if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this);//获取对应的ThreadLocal的变量值 if (e != null) { "unchecked") ( T result = (T)e.value; return result; } } return setInitialValue();//若当前线程还未创建ThreadLocalMap,则返回调用此方法在其中调用createMap方法 } /** * 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; } /** * 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 */ //为当前线程创建一个ThreadLocalMap的threadlocals,并将第一个值存入到当前map中 void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); } /** * 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); } /** * Removes the current thread's value for this thread-local * variable. If this thread-local variable is subsequently * {@linkplain #get read} by the current thread, its value will be * reinitialized by invoking its {@link #initialValue} method, * unless its value is {@linkplain #set set} by the current thread * in the interim. This may result in multiple invocations of the * {@code initialValue} method in the current thread. * * @since 1.5 */ public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); }
static class ThreadLocalMap { 298 //map中的每个节点Entry,其键key是ThreadLocal并且还是弱引用,这也导致了后续会产生内存泄漏问题的原因。 static class Entry extends WeakReference<ThreadLocal<?>> { Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } /** * 初始化容量为16,以为对其扩充也必须是2的指数 */ private static final int INITIAL_CAPACITY = 16; /** * 真正用于存储线程的每个ThreadLocal的数组,将ThreadLocal和其对应的值包装为一个Entry。 */ private Entry[] table; ///....其他的方法和操作都和map的类似 }
诡异的java.lang.IllegalMonitorStateException
真正的问题在于this.wait这个变量是一个Boolean,并且,在调用this.wait.wait()之前,this.wait执行了一次赋值操作:
this.wait = true;
Boolean型变量在执行赋值语句的时候,其实是创建了一个新的对象。简单的说,
在赋值语句的之前和之后,this.wait并不是同一个对象。
synchronzied(this.wait)绑定的是旧的Boolean对象,而this.wait.wait()使用的是新的Boolean对象。由于新的Boolean对象并没有使用synchronzied进行同步,所以系统抛出了IllegalMonitorStateException异常。
相同的悲剧还有可能出现在this.wait是Integer或者String类型的时候。
一个解决方案
是采用java.util.concurrent.atomic中对应的类型,比如这里就应该是AtomicBoolean。采用AtomicBoolean类型,可以保证对它的修改不会产生新的对象。