ThreadLocal爲Java併發提供了一個新的思路,它用來存儲Thread的局部變量,從而達到各個Thread之間的隔離運行。它被廣泛應用於框架之間的用戶資源隔離、事務隔離等。
一、內存泄露原因
ThreadLocal操作不當會引發內存泄漏,最主要的原因在於它的內部類ThreadLocalMap中的Entry的設計。
Entry繼承了WeakReference<ThreadLocal<?>>,即Entry的key是弱引用,所以key會在垃圾回收的時候被回收掉,而key對應的value則不會被回收,這樣會導致一種現象:key爲null,value有值。
key爲空的話value是無效數據,久而久之,value累加就會導致內存泄露。
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;
}
}
。。。。
二、怎麼解決這個內存泄漏問題
每次使用完ThreadLocal都調用它的remove()方法清除數據。因爲它的remove方法會主動將當前的key和value(Entry)進行清除。
/**
* 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);
}
}
/**
* 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;
}
}
}
e.clear()用於清除Entry的key,它調用的是WeakReference中的方法:this.refrent = null
/**
* Clears this reference object. Invoking this method will not cause this
* object to be enqueued.
*
* <p> This method is invoked only by Java code; when the garbage collector
* clears references it does so directly, without invoking this method.
*/
public void clear() {
this.referent = null;
}
expungeStaleEntry(i)用於清除Entry對應的value,這個後面會詳細講。
三、JDK開發者是如何避免內存泄漏的
ThreadLocal的設計者也意識到了這一點(內存泄漏),他們在一些方法中埋了對key=null的value擦除操作。
這裏拿ThreadLocal提供的get()方法舉例,它調用了ThreadLocalMap#getEntry()方法,對key進行了校驗和對null key進行擦除。
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
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;
}
如果key爲null,則會調用getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e)方法,在這個方法中,如果key == null,則調用expungeStaleEntry(int staleSlot);方法。
expungeStaleEntry(int staleSlot)方法完成了對key=null的key所對應的value進行賦空,釋放了空間避免內存泄漏。
同時它遍歷下一個key爲空的entry,並將value複製爲null,等待下次GC釋放掉其空間。
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;
}
同理,set()方法最終也是調用該方法(expungeStaleEntry)
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
}
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();
}
這樣做,也只能說儘可能避免內存泄漏,但並不完全解決內存泄漏這個問題。比如極端情況下我們只創建ThreadLocal但不調用set、get、remove等方法。所以最能解決問題的辦法就是用完ThreadLocal後手動調用remove()。
四、手動釋放ThreadLocal遺留存儲?怎麼去設計/實現?
這裏主要是強化一下手動remove的思想和必要性,設計思想與連接池類似。
包裝其父類remove方法爲靜態方法,如果是spring項目,可以藉助於bean的生命週期,再攔截器afterCompletion階段進行調用。
弱引用導致內存泄漏,那爲什麼key不設置爲強引用?
如果key設置爲強引用,當threadLocal實例釋放後,threadLocal=null,但是threadLocal會有強引用指向threadLocalMap、threadLocalMap.Entry又強引用threadLocal,這樣會導致threadLocal不能正常被GC回收。
弱引用雖然回引起內存泄漏,但是set、get、remove方法操作對null key進行擦除的補救措施,方案上略勝一籌。
線程執行結束後會不會自動清空Entry的value?
事實上,當currentThread執行結束後,threadLocalMap變得不可達從而被回收,Entry等也就都被回收了,但這個環境就要要求不對Thread進行復用,但是我們項目中經常會複用線程來提高性能,所以currentThread一般不會處於終止狀態。
五、Thread和ThreadLocal有什麼聯繫?
Thread和ThreadLocal是綁定的,ThreadLocal依賴於Thread去執行,Thread將需要隔離數據放到ThreadLocal(準確的講是ThreadLocalMap)中,來實現多線程處理。
六、Spring如何處理Bean多線程下的併發問題?
ThreadLocal天生爲解決相同變量的訪問衝突問題,所以這個對於spring的默認單例bean的都線程訪問是一個完美的解決方案。Spring也確實是用了ThreadLocal來處理多線程下相同變量併發的線程安全問題。
Spring如何保證數據庫事務在同一個連接下執行的?
要想實現jdbc事務,就必須實在同一個鏈接對象中操作,多個連接下事務就會不可控,需要藉助分佈式事務完成,那Spring如何保證數據庫事務在同一個連接下執行呢?
DateSourceTransactionManager是spring的數據源事務管理器,它會在你調用getConnection()的時候從數據庫連接池中獲取一個connection,然後將其與ThreadLocal綁定,十五完成後解除綁定,這樣就保證了事務在同一連接下完成。