先贊後看,養成習慣 🌹 歡迎微信關注
[Java編程之道]
,每天進步一點點,沉澱技術分享知識。
閒談ThreadLocal
前面在我的GitHub倉庫 V-LoggingTool 中有簡單的使用過ThreadLocal,主要用在了切面類中,功能上需要取到前置增強攔截到的用戶信息暫存,執行到後置增強時從該ThreadLocal中取出用戶信息並使用。
今天咱們就嘮嘮ThreadLocal的相關知識,瞭解一下他的數據結構、用法、原理等。咱們層層深入…
看了網上不少關於ThreadLocal的講解,源碼比較簡單但是對於Thread、ThreadLocal、ThreadLocalMap的關係講的有點晦澀,尤其是那張亙古不變的ThreadLocal的內部結構圖,額…我真的看了很久才明白是怎麼回事。
ThreadLocal工具類
ThreadLocal是一個本地線程副本變量工具類,主要用於將私有線程和該線程存放的副本對象做一個映射,各個線程之間的變量互不干擾。
官方說的還是比較明白了,提煉關鍵字工具類
,在我看來ThreadLocal就是提供給每個線程操作變量的工具類,做到了線程之間的變量隔離目的
內部結構圖
接下來就是看圖說話:
- 每個Thread線程內部都有一個ThreadLocalMap。
- Map裏面存儲線程本地對象ThreadLocal(key)和線程的變量副本(value)。
- Thread內部的Map是由ThreadLocal維護,ThreadLocal負責向map獲取和設置線程的變量值。
- 一個Thread可以有多個ThreadLocal。
每個線程都有其獨有的Map結構,而Map中存有的是ThreadLocal爲Key變量副本爲Vaule的鍵值對,以此達到變量隔離的目的。
平時是怎麼使用ThreadLocal的?
package threadlocal;
/**
* @Auther: Xianglei
* @Company: Java編程之道
* @Date: 2020/7/2 21:44
* @Version 1.0
*/
public class main {
private static ThreadLocal<String> sThreadLocal = new ThreadLocal<>();
public static void main(String args[]) {
sThreadLocal.set("這是在主線程中");
System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
//線程a
new Thread(new Runnable() {
@Override
public void run() {
sThreadLocal.set("這是在線程a中");
System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
}
}, "線程a").start();
//線程b
new Thread(new Runnable() {
@Override
public void run() {
sThreadLocal.set("這是在線程b中");
System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
}
}, "線程b").start();
//線程c
new Thread(() -> {
sThreadLocal.set("這是在線程c中");
System.out.println("線程名字:" + Thread.currentThread().getName() + "---" + sThreadLocal.get());
}, "線程c").start();
}
}
輸出結果如下
線程名字:main---這是在主線程中
線程名字:線程b---這是在線程b中
線程名字:線程a---這是在線程a中
線程名字:線程c---這是在線程c中
Process finished with exit code 0
可以看出每個線程各通過ThreadLocal對自己ThreadLocalMap中的數據存取並沒有出現髒讀的現象。就是因爲每個線程內部已經存儲了ThreadLocal爲Key變量副本爲Vaule的鍵值對。(隔離了)
可能你有點懵,ThreadLocal是怎麼把變量複製到Thread的ThreadLocalMap中的?
咱們接着嘮…
當我們初始化一個線程的時候其內部幹去創建了一個ThreadLocalMap的Map容器
待用。
public class Thread implements Runnable {
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
}
當ThreadLocalMap被創建加載的時候其靜態內部類Entry也隨之加載,完成初始化動作。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
到此,線程Thread內部的Map容器初始化完畢,那麼它又是如何和ThreadLocal纏上關係,ThreadLocal又是如何管理鍵值對的關係。
ThreadLocal探析
我們就其核心方法分析一下內部的邏輯,同時解答上述存在的疑問:
-
set()方法用於保存當前線程的副本變量值。
-
get()方法用於獲取當前線程的副本變量值。
-
initialValue()爲當前線程初始副本變量值。
-
remove()方法移除當前線程的副本變量值。
set方法
/**
* 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);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
解說一下你就懂了:
當我們在Thread內部調用set方法時:
- 第一步會去獲取
調用當前方法的線程Thread
。 - 然後順其自然的拿到當前
線程內部
的ThreadLocalMap
容器。 - 最後就把變量
副本
給丟進去。
沒了…懂了嗎,ThreadLocal(就認爲是個維護線程內部變量的工具!)只是在Set的時候去操作了Thread內部的·ThreadLocalMap
將變量拷貝到了Thread內部的Map容器中,Key就是當前的ThreadLocal,Value就是變量的副本。
get方法
/**
* 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() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
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;
}
- 獲取當前線程的ThreadLocalMap對象
- 從map中根據this(當前的threadlocal對象)獲取線程存儲的Entry節點。
- 從Entry節點獲取存儲的對應Value副本值返回。
- map爲空的話返回初始值null,即線程變量副本爲null。
remove方法
清除Map中的KV
/**
* 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
* <tt>initialValue</tt> method in the current thread.
*
* @since 1.5
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* 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;
}
}
}
下面再認識一下ThreadLocalMap
,一個真正存儲(隔離)數據的東西。
ThreadLocalMap
ThreadLocalMap是ThreadLocal的內部類
,實現了一套自己的Map結構,咱們看一下內部的繼承關係就一目瞭然。
其Entry使用的是K-V方式來組織數據,Entry中key是ThreadLocal對象,且是一個弱引用(弱引用,生命週期只能存活到下次GC前
)。
對於弱引用
引發的問題我們最後再說
。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
ThreadLocalMap的成員變量
static class ThreadLocalMap {
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
}
HashCode 計算
ThreaLocalMap中沒有采用傳統的調用ThreadLocal的hashcode方法(繼承自object的hashcode),而是調用nexthashcode
,源碼如下:
private final int threadLocalHashCode = nextHashCode();
private static AtomicInteger nextHashCode = new AtomicInteger();
//1640531527 能夠讓hash槽位分佈相當均勻
private static final int HASH_INCREMENT = 0x61c88647;
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
Hash衝突
和HashMap的最大的不同在於,ThreadLocalMap解決Hash衝突的方式就是簡單的步長加1或減1及線性探測,尋找下一個相鄰的位置。
/**
* Increment i modulo len.
*/
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
/**
* Decrement i modulo len.
*/
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
ThreadLocalMap採用線性探測的方式解決Hash衝突的效率很低,如有大量不同的ThreadLocal對象放入map中時發送衝突。所以建議每個線程只存一個變量(一個ThreadLocal)就不存在Hash衝突的問題,如果一個線程要保存set多個變量,就需要創建多個ThreadLocal,多個ThreadLocal放入Map中時會極大的增加Hash衝突的可能。
清楚意思嗎?當你在一個線程需要保存多個變量時,你以爲是多次set?你錯了你得創建多個ThreadLocal,多次set的達不到存儲多個變量的目的。
sThreadLocal.set("這是在線程a中");
Key的弱引用問題
看看官話,爲什麼要用弱引用。
To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys.
爲了處理非常大
和生命週期
非常長的線程,哈希表使用弱引用作爲 key。
- 生命週期長:暫時可以想到線程池中的線程
ThreadLocal在沒有外部對象強引用時如Thread,發生GC時弱引用Key會被回收,而Value是強引用不會回收,如果創建ThreadLocal的線程一直持續運行如線程池中的線程,那麼這個Entry對象中的value就有可能一直得不到回收,發生內存泄露。
-
key 如果使用強引用:引用的ThreadLocal的對象被回收了,但是ThreadLocalMap還持有ThreadLocal的強引用,如果沒有手動刪除,ThreadLocal不會被回收,導致Entry內存泄漏。
-
key 使用弱引用:引用的ThreadLocal的對象被回收了,由於ThreadLocalMap持有ThreadLocal的弱引用,即使沒有手動刪除,ThreadLocal也會被回收。value在下一次ThreadLocalMap調用set,get,remove的時候會被清除。
Java8中已經做了一些優化如,在ThreadLocal的get()、set()、remove()方法調用的時候會清除掉線程ThreadLocalMap中所有Entry中Key爲null的Value,並將整個Entry設置爲null,利於下次內存回收。
Java8中for循環遍歷整個Entry數組,遇到key=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;
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
通常ThreadLocalMap的生命週期跟Thread(注意線程池中的Thread)一樣長,如果沒有手動刪除對應key(線程使用結束歸還給線程池了,其中的KV不再被使用但又不會GC回收,可認爲是內存泄漏),一定會導致內存泄漏,但是使用弱引用可以多一層保障:弱引用ThreadLocal會被GC回收,不會內存泄漏,對應的value在下一次ThreadLocalMap調用set,get,remove的時候會被清除
,Java8已經做了上面的代碼優化。
總結
- 每個ThreadLocal只能保存一個變量副本,如果想要一個線程能夠保存多個副本以上,就需要創建多個ThreadLocal。
- ThreadLocal內部的ThreadLocalMap鍵爲弱引用,會有內存泄漏的風險。
- 每次使用完ThreadLocal,都調用它的remove()方法,清除數據。
更多精彩好文盡在:Java編程之道
🎁
歡迎各位好友前去關注!🌹