在開發過程中碰到過 ThreadLocal ,一直都沒有認真看看究竟是怎麼實現的,於是花了點時間理解了下,做一個筆記算是分享下。
源碼基於 Android SDK 26 JDK 1.8
打算從 ThreadLocal 中的常見操作進行尋找原理,New 、Set 、Get 、 Remove 進行分析。如果沒有耐心的看完的話,建議直接點 【二.2.3】replaceStaleEntry()。
【一】ThreadLocal 結構
首先大概瞄一眼 ThreadLocal 結構。
【一】
public class ThreadLocal<T> {
……
public ThreadLocal() {}
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;
}
}
/**
* 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.
*/
//【存放節點的table】
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
……
}
}
首先按照我們常用的使用方式。
ThreadLocal<T> mThreadLocal = new ThreadLocal();
按照這個構造函數點進去,發現啥操作都沒有。那就從常見的set入手吧。
【二】ThreadLocal.set()
【二】
public void set(T value) {
//【新建一個線程並指向了當前線程】
Thread t = Thread.currentThread();
//【從當前線程中拿到 ThreadLocalMap】
ThreadLocalMap map = getMap(t);【二.1】
if (map != null)
map.set(this, value);【二.2】
else
createMap(t, value);【二.3】
}
然後我們來看看這三個方法。
【二.1】getMap()
【二.1】
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//【既然是線程裏的屬性,咱們就找找 Thread 有沒有這個東西】
public class Thread implements Runnable {
……
/* ThreadLocal values pertaining to this thread.
* This map is maintained by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
……
}
果然有這個屬性,然後在 Thread 當中查找是否有相關調用初始化
暫時沒有找到,我們就默認爲 null 。先看 if (map != null) 的情況。
【二.3】createMap()
【二.3】
void createMap(Thread t, T firstValue) {
//【初始化t線程的ThreadLocalMap。】
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
//【從構造方法從也看出,如果是走這個構造方法。】
//【第一次創建是拿到了一個鍵值對,初始化後會直接插入新數據。】
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
//【初始化節點數組】
table = new Entry[INITIAL_CAPACITY]; 【二.3.1】
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);【二.3.2】
//【插入第一個節點,調整節點數組大小,設置預警閥值。】
table[i] = new Entry(firstKey, firstValue);
size = 1;
//【根據最大長度設置預警值】
setThreshold(INITIAL_CAPACITY);
}
/**
* The initial capacity -- 【MUST be a power of two.】
*/
private static final int INITIAL_CAPACITY = 16;
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
觀察 ThreadLocalMap 的構造函數,是當需要開始放進數據的時候,纔會初始化。
【二.3.1】INITIAL_CAPACITY
INITIAL_CAPACITY 的註釋,我標記了下。
什麼叫 power-of-two ,這個要是說成兩種的力量?功率?
聽着感覺怎麼和計算機也不掛鉤,咱們去google(baidu)下。
能看到一個解釋類似的解釋: power() :返回數字乘冪的計算結果。
咱們猜測下 power of two,是不是2的多少次方。
INITIAL_CAPACITY - 1 16 - 1 = 15。一個數好像不好說明問題,咱們多試幾個2的n次方-1來試試。看看能不能找到什麼規律。
3 = 22 - 1 ; 7 = 23 - 1 ; 15 = 24 - 1; 31 = 25 - 1 ; 63 = 26 - 1
然後都換成2進制看看。(只看八位)
3 = 00000011 ; 7 = 00000111 ; 15 = 00001111 ; 31 = 00011111 ; 63 = 00111111
發現0和1很整齊嘛,彷彿是有某種規律,咱們來看下下一個。 ThreadLocal.threadLocalHashCode.
【二.3.2】ThreadLocalHashCode
【二.3.2】
public class ThreadLocal{
……
//【原來還是一個方法,那我們繼續跳轉。】
private final int threadLocalHashCode = nextHashCode();
……
//【調用自身的自身的hasconde獲取再增加。】
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
private static AtomicInteger nextHashCode = new AtomicInteger();
/**
* The difference between successively generated hash codes - turns
* implicit sequential thread-local IDs into near-optimally spread
* multiplicative hash values for 【power-of-two-sized tables.】
*/
private static final int HASH_INCREMENT = 0x61c88647;
……
}
public class AtomicInteger{
……
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
//【從這段註釋來看,應該是將原值,加上delta的值。】
public final int getAndAdd(int delta) {
return U.getAndAddInt(this, VALUE, delta);
}
……
}
不斷累加 HASH_INCREMENT 作爲自己的 hashCode。從剛剛的結果來看, INITIAL_CAPACITY - 1 得出了一堆 01 規律的數字,來觀察下。
如果它與一個數進行 & 運算,高位的數據按位與 0 & 計算,都是 0 ;低位數據按位與 1 & 計算,都是原數據。
是不是這樣就忽略高位,保留低位啦。這樣就保證了 & 之後的數,是小於等於 len - 1。剛好也是從 table[0] ~ table[len-1]。
剛分析了 map == null 的情況,來接下來分析下,如果 map != null 的情況。
【二.2】set()
Code【二.2】
private void set(ThreadLocal<?> key, Object value) {
//【指向ThreadLocalMap中的節點集合】
Entry[] tab = table;【二.2.1】
int len = tab.length;
//【根據散列按位進行運算出 index。】
int i = key.threadLocalHashCode & (len-1);
//【從index往後循環查找。判斷是先找到key,還是先碰到一個 table 中一個空的位置。】
for (Entry e = tab[i];e != null;e = tab[i = nextIndex(i, len)]) {【二.2.2】
//【如果從這個循環裏結束,就說明是先找到對應的節點。】
ThreadLocal<?> k = e.get();
//【如果發現之前ThreadLocal存儲過,則修改舊值後返回。】
if (k == key) {
e.value = value;
return;
}
//【如果是ThreadLocal == null,看名字是一些替換舊數據的操作並返回。】
if (k == null) {
replaceStaleEntry(key, value, i);【二.2.3】
return;
}
}
//【如果走這,則說明先碰到 table 中空的位置,在index位置放進新數據。】
tab[i] = new Entry(key, value);
int sz = ++size;
//【看名字又是一些清除的操作,進行預警值的判斷之後還有一次rehash()操作。】
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();【二.2.4】
}
好吧,發現這次挑戰要多一點。一個一個看。
【二.2.1】ThreadLocal.ThreadLocalMap.Entry
【二.2.1】
//需要說明的就是,鍵是ThreadLocal類型,並且是弱引用的.
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
來看個小例子,比如咱們先這麼操作下,建兩個 ThreadLocal。
//【新建兩個ThreadLocal,並存放不同的類。】
ThreadLocal<String> t1 = new ThreaLocal();
ThreadLocal<Integer> t2 = new ThreaLocal();
//【thread1 】
t1.set("One");
t2.set(1);
//【thread2】
t1.set("Two");
t2.set(2);
//【然後兩個 Thread Entry[] tables 應該就差不多是這種.】
//【thread1】
Entry[] table = [<t1,"One">,<t2,1>];
//【thread2】
Entry[] table = [<t1,"Two">,<t2,2>];
//【測試下,貼部分代碼 安卓下測試的。】
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//【主線程設置一次】
t1.set("One");
t2.set(1);
new Thread(new Runnable() {
@Override
public void run() {
//【新開線程再設置一次】
t1.set("Two");
t2.set(2);
//【新線程取一次結果】
Log.w(TAG, " new Thread t1.get() : " + t1.get() + " ; t2.get() : " + t2.get());
}
}).start();
//【主線程再取一次結果】
Log.w(TAG, "main Thread t1.get() : " + t1.get() + " ; t2.get() : " + t2.get());
}
來運行看看結果。
**
取值的時候就會先拿到對應線程的 ThreaLocalMap ,再通過對比 table 中每個節點中 key 的值,獲得對應的值。
【二.2.2】nextIndex()
【二.2.2】
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
這個方法簡單,小於長度時加1向後移動,不過那如果等於長度之後,就返回0.是不是可以理解爲,向後一直循環,滿了之後又從0開始,是一個循環的數組?
table[0] ~ table[len-1] -> table[0] 從 0 到末尾,又重新指向 0。
【二.2.3】replaceStaleEntry()
【二.2.3】
private void replaceStaleEntry(ThreadLocal<?> key, Object value,int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
//【先存放原計劃 index】
int slotToExpunge = staleSlot;
//【向前循環尋找,是否存在節點的鍵爲 null ,如果存在則向左一直查找並存儲最靠左的 index,直到節點指向了一個 null 的位置】
//【這個和之前的nextIndex()差不多。這個是向前循環】
for (int i = prevIndex(staleSlot, len);(e = tab[i]) != null;i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
//【從原計劃 index 向後查找】
for (int i = nextIndex(staleSlot, len);(e = tab[i]) != null;i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
// If we find key, then we need to swap it
// with the stale entry to【maintain hash table order.】
// The newly stale slot, or any other stale slot
// encountered above it, can then be sent to expungeStaleEntry
// to remove or rehash all of the other entries in run.
if (k == key) {
//【如果判斷是相同的key,則先替換舊值,將之前在原計劃index的數據,移到key相等的位置】
//【再把替換過的節點插入到原計劃index 以保證之前的hash順序一致。如上的註釋】
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
//【如果上一步向左掃描都沒有節點鍵爲null的情況,因爲 staleSlot 目前沒有改變】
//【反推如果 slotToExpunge == staleSlot 成立,則說明上一步向左掃描沒有找到節點的鍵爲null情況(碰到null節點前)】
if (slotToExpunge == staleSlot)
slotToExpunge = i;
//【將i的值作爲清除的index傳入,就是兩種情況,左邊有節點鍵爲null的index,或者此處交換之後的index】
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
// If we didn't find stale entry on backward scan, the
// first stale entry seen while scanning for key is the
// first still present in the run.
//【如果沒有找到,slotToExpunge 則等於從staleSlot右邊算,第一個碰到節點鍵爲null的index】
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// If key not found, put new entry in stale slot
//【如果沒有找到該ThreadLocal,則在原計劃位置插入新Enrty】
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
//【如果兩個數據不相等則說明右邊存在鍵爲null的Enrty,然後從那個index開始清除】
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);【*】
}
好吧,長方法又來了 ……
不過 … 縱使困頓難行,亦當砥礪奮進嘛。
- 先存放最先計劃替換的 index ,先向左查詢,判斷是否有鍵爲 null 的節點,有的話,就替換一次 slotToExpunge 的值,一直查找存儲最左邊的,直到碰到
null 的位置。- 向右查找,是否存在 key 相同的節點。
- 如果向右能找到,則替換節點 value ,並且與 staleSlot 位置進行交換,保證之前的散列順序,然後從 slotToExpunge 開始清理。
- 如果不能找到,判斷上一步是否在左邊查找到鍵爲 null 的節點,如果沒有向左移動過,則從 staleSlot + 1 處開始清理。
- 如果沒有找到節點,則在最開始位置進行插入數據,並判斷是否需要清理
- 如果向左和向右查找的時候,都是正常的話,那麼 staleSlot == staleToExpunge ,則不需要清理。
- 否則就從 slotToExpunge 開始清理。
好吧,文字描述了,估計還是有點抽象,還是來幾張圖好說明一下。先分析第一個循環,向左循環查找。
接下來分析後面的循環,向右循環查找。
關於 staleToExpunge ,只要它向左移動過之後,清理肯定是從左開始的,並且因爲中間是連續的,所以與 staleSlot 的位置就沒有關係了。
把這個拿下之後,就大概能明白清理的思路了,剩下就是分析清理的方法了 expungeStaleEntry() , cleanSomeSlots() 。
【*】
/**
* Expunge a stale entry by rehashing any possibly colliding entries
* lying between staleSlot and the next null slot. This also expunges
* any other stale entries encountered before the trailing null. See
* Knuth, Section 6.4
*
* @param staleSlot index of slot known to have null key
* @return the index of the next null slot after staleSlot
* (all between staleSlot and this slot will have been checked
* for expunging).
*/
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot.
//【注意】這裏是先置空value,再置空key。
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// Rehash until we encounter null
Entry e;
int i;
//【從要清除的index開始向後掃描】
for (i = nextIndex(staleSlot, len);(e = tab[i]) != null;i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
//【如果碰到節點鍵爲null,會釋放掉值,並置空table[i].調整table大小】
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
int h = k.threadLocalHashCode & (len - 1);
//【如果碰到鍵不爲null,則會重新算出新index,如果不在原來的位置,置空原位置,就線性向後一直探測到null節點並放入】
if (h != i) {
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
//【向後探測直到存在null的位置放入數據】
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
此處返回的 i,已經是 for 循環不成立的時候,就是碰到空節點的時候。
【*】
private boolean cleanSomeSlots(int i, int n) {
boolean removed = false;
Entry[] tab = table;
int len = tab.length;
do {
i = nextIndex(i, len);
Entry e = tab[i];
if (e != null && e.get() == null) {
n = len;
removed = true;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
從剛剛調用時傳入的數值。 cleanSomeSlots(expungeStaleEntry(slotToExpunge), len) ;
expungeStaleEntry() 返回爲一個空鍵節點 index ,cleanSomeSlots() 則從 index 下一個開始查找。
如果查找到的節點不爲 null ,但是鍵爲 null ,則從該處開始清理數據。
清理一次,則 n 向右移一位,table 大小縮小一半( 1 變 0 肯定是不算哈)。
其實此處沒太想通退出循環的條件是連續 logN 次 沒找到鍵爲 null 的節點。
有個小細節:nextIndex 與 preIndex 爲什麼從 ±1開始計算,而不是從傳入的值計算,從方法的調用來看。
傳入的一般是節點爲 null 的 index ,如果直接從 index 開始進行循環查找,則直接就中斷了。
【二.2.4】rehash()
【二.2.4】
private void rehash() {
//【清理所有老舊的數據(即鍵爲null的節點。)】
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
//【如果清理之後,仍大於預警值的3/4,則兩倍擴容】
if (size >= threshold - threshold / 4)
resize();
}
/**
* Expunge all stale entries in the table.
*/
//【循環查找清理】
private void expungeStaleEntries() {
Entry[] tab = table;
int len = tab.length;
for (int j = 0; j < len; j++) {
Entry e = tab[j];
if (e != null && e.get() == null)
expungeStaleEntry(j);
}
}
/**
* Double the capacity of the table.
*/
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null; // Help the GC【幫助垃圾回收】
} else {
int h = k.threadLocalHashCode & (newLen - 1);
//【向後線性探測null位置插入節點】
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
//【設置預警值】
setThreshold(newLen);
size = count;
table = newTab;
}
set 方法就差不多分析完了,真的是有點長,不過基本把前面的思路理清之後,後面的幾個方法也沒啥難度了。
說完 set 肯定是有 get 的。
【三】ThreadLocal.get()
Code【三】
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
//【和前面set一樣,如果ThreadLocalMap != null &&
// ThreadLocalMap.get() != null ,會根據鍵進行對應的查找,並向上轉型爲T返回。】
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
//【如果ThreadLocalMap == null 或者 ThreadLocalMap.get() == null.】
//【則進行返回初始化值】
return setInitialValue();
}
//【接下來看看初始化值是怎麼回事】
private T setInitialValue() {
//【默認返回null】
T value = initialValue();
Thread t = Thread.currentThread();
//【從線程t中查找是否ThreadLocalMap == null ?】
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
//【說明第一次初始化時,都是 null,無論後面 map 是否爲 null】
protected T initialValue() {
return null;
}
createMap() 在【二.3】中已經分析過了。
map.set(this, value) 在【二.2】中已經分析過了,類似與 set 方法。
接下來看 remove() 。
【四】ThreadLocal.remove()
Code【四】
public void remove() {
//【獲取當前線程的ThreadLocalMao,如果存在則根據當前的ThreadLocal查找值】
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;
//【根據hash值算出index】
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;
}
}
}
到這基本就算分析完了,主要的是 replaceStaleEntry() 方法,如果把這個理解透的話,基本就差不多明白了。
留一個問題:前面一直在說節點鍵爲 null 的情況,有沒有反應過來什麼情況下節點的鍵爲 null ,如果沒有反應過來的話。
可以去看下 ThreadLocalMap.Entry 看了構造函數之後應該就能明白了。
【五】總結:
在每個線程中都存在一個 ThreadLocalMap ,它有一個節點數組 Entry<ThreadLocal,value>[],每個 ThreadLocal 就是對應的鍵, T 就是對應的 value 類型。
ThreadLocal 會在插入新數據時會清理老舊的數據。如果不及時清理,一是影響了後續數據的插入,二是影響了 value 的回收。
其他容器類也存在長度爲 2 的指數情況,通過 hash值 與 len - 1 來獲取數據存放的 index 。
ThreadLocal 只是類似在每個線程都存放一個自己能使用的變量,如果你需要多個線程讀寫同一個數據,那麼還是需要用 鎖 機制或者 CAS 操作來保證數據的同步與正確性。
能力有限,可能存在一些問題或者不足之處,煩請指出,感謝。
要是覺得可以的話,麻煩點個贊表示支持。😂