「ThreadLocal簡單解析」
一. ThreadLocal有何作用?
-
ThreadLocal
為線程提供了獨有的
局部變量,每個線程私有。在Android
的Handler
消息機制中就使用到了ThreadLocal
婿脸,而平時開發(fā)過程中茫虽,使用的場景并不是很多贸街,主要可以實現(xiàn):存儲線程的信息如id继准,線程特有的變量信息等(線程私有避免了并發(fā)不安全問題)搜立。源碼中的定義:
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code 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
泛型添加,可以保存任意的對象:
public class ThreadLocal<T> {
//泛型T
}
二刮吧、內部的數(shù)據(jù)結構
-
ThreadLocal
存儲是以Key-Value
的方式湖饱,但是不同于常用的map
,內部實現(xiàn)了一個ThreadLocalMap
:
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
}
-
Entry
中的Key
是以弱引用的持有了ThreadLocal
杀捻,而Value
是強引用井厌,看代碼可能不太好理解,看看結構圖:
不同于普通
map
存儲特點致讥,ThreadLocalMap
提供了set(T value)
方法仅仆,具體看看這里怎樣實現(xiàn)的:
public void set(T value) {
//step1
Thread t = Thread.currentThread();
//step2
ThreadLocalMap map = getMap(t);
if (map != null)
//不同的ThreadLocal對象,對應不同的key垢袱,也即 Key(ThreadLocal)-Value(傳入的值) step3
map.set(this, value);
else
createMap(t, value); //step4
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//Thread類的成員變量
ThreadLocal.ThreadLocalMap threadLocals = null;
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
//step3中
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
//不同的ThreadLocal代表不同的key墓拜,通過set設置不同的value;一一對應保存在 Entry數(shù)組之中惶桐。后續(xù)取值時顯然數(shù)組隨機訪問效率更高撮弧。
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();
}
1.稍微總結一下:
-
set(T value)
時其實就是拿到當前操作的線程Thread
并為其內部的成員變量ThreadLocalMap
賦值的過程潘懊。 - 一個線程可以包含多個
ThreadLocal
對象的姚糊,而這些ThreadLocal-value
對象被包裝成Entry
被存儲到了ThreadLocalMap
當中(本質還是數(shù)組)。
2.再來看看是如何取值的:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
//當ThreadLocal調用get()授舟,其實相當于為map傳入了key救恨,以key獲得value
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
//還是為threadLocals賦值操作
return setInitialValue();
}
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;
}
protected T initialValue() {
return null;
}
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;
}
- table數(shù)組通過下標i取值,如果e(ThreadLocalMap.Entry對象)為空释树,調用了
getEntryAfterMiss()
肠槽,這個方法內主要作用就是將key為null對應的value清除掉。
三奢啥、為什么存在內存泄漏秸仙?
上述提到
Entry
用于存儲鍵值對,但是key
是弱引用TreadLocal
桩盲,而value
使用的是強引用寂纪,弱引用在下次GC
的收集發(fā)生時會被回收導致key
為空,此時value
作為強引用還是存在的。TreadLocal
在設計之初是考慮到內存泄漏問題的捞蛋,包括set() remove() get()
幾個方法在被調用的時候孝冒,都對key
為空的情況做了清理。那么
key
為什么不設計成強引用呢拟杉?現(xiàn)在假設key
被設計成強引用庄涡,那么回憶之前那張引用圖,堆中的TreadLocal
對象就存在兩個強引用指向搬设。一個是棧中(ThreadLocal被new出來的)穴店,一個是key。-
如果開發(fā)者顯式的斷開引用
threadLocal = null
拿穴,此時key還是強引用指向堆中的ThreadLocal
對象迹鹅。那么堆中的對象是無法被回收的,只有等到線程生命周期結束贞言,threadLocals
才會被置為空斜棚,entry
才會釋放。那么可以認為entry
已經造成內存泄漏了该窗。
當在使用線程池復用線程時弟蚀,此時使用了ThreadLocal來保存數(shù)據(jù)的話,一定要做適當?shù)尼尫挪僮餍锸В粌H可能帶來泄漏問題义钉。甚至造成業(yè)務數(shù)據(jù)的錯亂。