- 概述
- 大致原理
- 问题
- 重要源代码
- ThreadLocalMap的存储实体Entry">ThreadLocalMap的存储实体Entry
- ThreadLocalMap中的set()方法">ThreadLocalMap中的set()方法
- ThreadLocalMap中的get()方法">ThreadLocalMap中的get()方法
- ThreadLocalMap中的remove()方法">ThreadLocalMap中的remove()方法
概述
- 生命周期跟随Thread一起的一种存储临时变量的方式。
- 是一种解耦传参的方式,让一些专属于线程的变量可以通过简易的方式获取。
- 本质是线程的一个成员变量 ThreadLocalMap,而且这个Map使用开放寻址法实现的。
广为人知的事
- ThreadLodal是弱引用,垃圾回收时会死亡。
- 这个认知是不完全正确的
大致原理
声明一个ThreadLocal变量,会作为key。
- 调用ThreadLocal中的api存储数据,其内部会把数据存储到当前线程Thread上的ThreadLocalMap属性中。
- 存储的单位是Entry,ThreadLocal实例会作为这个Entry的key,真正的数据值会作为value。
- 每次垃圾回收后,会把ThreadLocal清除,Entry的key就成了null
每当get()或set()方法时,如果原本位置上Entry的key为null,就会把key为null的值清理掉。
问题
首先在线程会被复用的情况下讨论这些才有意义(比如线程池),否则线程回收的同时它相关的一切都回收了,就不必纠结内存泄漏问题了。
- ThreadLocal虽然是弱引用,但是仍然有引发内存泄漏的风险
- 虽然ThreadLocal本身是弱引用,系统回收时会删除,但是ThreadLocal只是作为key存在Thread的ThreadLocalMap中。
- Map是以数组中Entry的形式存储数据的,Entry中ThreadLocal对象作为key,value对象作为值。
- 也就是说,key是ThredaLocal,是弱引用,value却不是。
- 经过一次垃圾回收后,ThreadLocalMap中会留下一下key为null,value还是原值的Entry。
-
解决
ThreadLocal实现本身有一定的解决能力,为null的ThreadLocal对应的key被触发get()或set()方法时,会清理null值。
- 最正确的解决方法
- 每次用完ThreadLoca变量后调用remove()
重要源代码
ThreadLocalMap的存储实体Entry
/**
* 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;
}
}
ThreadLocalMap中的set()方法
/**
* Set the value associated with key.
*
* @param key the thread local object
* @param value the value to be 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中的get()方法
/**
* Get the entry associated with key. This method
* itself handles only the fast path: a direct hit of existing
* key. It otherwise relays to getEntryAfterMiss. This is
* designed to maximize performance for direct hits, in part
* by making this method readily inlinable.
*
* @param key the thread local object
* @return the entry associated with key, or null if no such
*/
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);
}
/**
* 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)
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
ThreadLocalMap中的remove()方法
/**
* Remove the entry for key.
*/
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();
expungeStaleEntry(i);
return;
}
}
}