1.ThreadLocalMap.Entry
key:指向key的是弱引用
value:強引用
public class ThreadLocal<T> {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); //指向key的弱引用value = v; //指向value的是強引用}}}
}
2.hash計算
- nextHashCode是static的,說明是ThreadLocal類共用
- 在上一個ThreadLocal的hash的基礎上增加HASH_INCREMENT
public class ThreadLocal<T> {//所有ThreadLocal類公用private static AtomicInteger nextHashCode = new AtomicInteger();private static final int HASH_INCREMENT = 0x61c88647;private final int threadLocalHashCode = nextHashCode();//每次在上一個hash的基礎上增加HASH_INCREMENTprivate static int nextHashCode() {return nextHashCode.getAndAdd(HASH_INCREMENT);}
}
HASH_INCREMENT
的值是 0x61c88647,它是黃金分割比例乘以 2^31,這樣可以使得步長增量更加分散,減小碰撞的概率,提高 ThreadLocal
的性能。
黃金分割率是一個數學和藝術上的常數,通常用希臘字母 φ(phi)表示,其近似值為1.618033988749895。
3.怎么處理hash沖突
ThreadLocalMap 使用線性探測法(linear probing)來處理哈希沖突。線性探測法是一種解決哈希沖突的簡單方法,其中如果一個槽已經被占用,就線性地查找下一個可用的槽,直到找到一個可用槽為止。
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1); //這里計算index跟HashMap一樣
如果i被占用,則用nextIndex(i, len)計算下一個索引,看是否被占用
public class ThreadLocal<T> {static class ThreadLocalMap {/*** The table, resized as necessary.* table.length MUST always be a power of two.*/private Entry[] table;/*** Increment i modulo len.* 每次i+1,如果i+1<len,則返回0*/private static int nextIndex(int i, int len) {return ((i + 1 < len) ? i + 1 : 0);}/*** 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); //這里計算index跟HashMap一樣//下一個元素:i+1,如果i+1越界,怎為0for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) {ThreadLocal<?> k = e.get(); //獲取keyif (k == key) { //key相等e.value = value; //更新value的值return;}if (k == null) {//說明這里放入的是無效數據,可以放入新數據replaceStaleEntry(key, value, i);//放入數據,再做些無效數據清理工作return;}//e不為null;k不為null;說明被正常的元素占用了,則到下一個索引}//tab[i]為null,退出了循環tab[i] = new Entry(key, value); //放入數組int sz = ++size;//如果沒有移除數據,同時size大于thresholdif (!cleanSomeSlots(i, sz) && sz >= threshold){rehash(); //擴容}}}
}
4.擴容
- 先清理所有的stale數據;
- 如果size大于等于threshold*3/4,進行擴容;
public class ThreadLocal<T> {static class ThreadLocalMap {private void rehash() {expungeStaleEntries(); //清理stale數據// Use lower threshold for doubling to avoid hysteresis//數據大小大于或者等于threshold的3/4后,進行擴容if (size >= threshold - threshold / 4)resize();}}
}
4.1.expungeStaleEntries-清理所有的stale數據
循環遍歷執行expungeStaleEntry方法;
expungeStaleEntry方法:
(1)從table清除位于staleSlot的Entry;
(2)從staleSlot往后遍歷table,直到table[i]為null
????????如果table[i]為stale元素,從table清除該元素;
????????如果table[i]不為stale元素,計算table[i]中的Entry本來應該放入的index,從那個index開始往后找Entry應該放入的位置A,將該Entry放入位置A;
?expungeStaleEntries
public class ThreadLocal<T> {static class ThreadLocalMap {/*** 清除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){//e不為null且key為nullexpungeStaleEntry(j);}}}private int expungeStaleEntry(int staleSlot) {Entry[] tab = table;int len = tab.length;// expunge entry at staleSlottab[staleSlot].value = null; //value設為nulltab[staleSlot] = null; //entry設為nullsize--; //size減1// Rehash until we encounter nullEntry e;int i;for (i = nextIndex(staleSlot, len); (e = tab[i]) != null;i = nextIndex(i, len)) {ThreadLocal<?> k = e.get();if (k == null) {//如果元素不為null,但是key為nulle.value = null;tab[i] = null;size--;} else {//不是stale元素的話,重新將這個元素放到合適的位置int h = k.threadLocalHashCode & (len - 1); //計算indexif (h != i) {//本來應該放在h的位置,因為沖突的關系被放到了i//h->>>>>>>>>>>i 看這中間有沒有為null的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開始找e為null的indexh = nextIndex(h, len);}tab[h] = e; //把e放在合適的index}}}return i; //返回的i是Entry為null的索引}}
}
4.2.ThreadLocalMap.resize-擴容
擴容:
新table的長度為老table長度的2倍;
遍歷老table:
? ? ? ? table[j]不為null:
? ? ? ? ? ? ? ? key為null,設置value為null;
? ? ? ? ? ? ? ? key不為null,根據新table的length計算index,將該元素放入合適的位置;
public class ThreadLocal<T> {static class ThreadLocalMap {private void resize() {Entry[] oldTab = table;int oldLen = oldTab.length;int newLen = oldLen * 2; //新len為老len的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) {//stale元素e.value = null; // Help the GC} else {int h = k.threadLocalHashCode & (newLen - 1); //重新計算indexwhile (newTab[h] != null){//找到該元素該放的位置h = nextIndex(h, newLen);}newTab[h] = e;count++;}}}setThreshold(newLen); //更新thresholdsize = count;table = newTab;}}
}
5.ThreadLocalMap.replaceStaleEntry
public class ThreadLocal<T> {/*** ThreadLocalMap is a customized hash map suitable only for* maintaining thread local values. No operations are exported* outside of the ThreadLocal class. The class is package private to* allow declaration of fields in class Thread. To help deal with* very large and long-lived usages, the hash table entries use* WeakReferences for keys. However, since reference queues are not* used, stale entries are guaranteed to be removed only when* the table starts running out of space.*/static class ThreadLocalMap {/*** Decrement i modulo len.*/private static int prevIndex(int i, int len) {return ((i - 1 >= 0) ? i - 1 : len - 1);}/*** Replace a stale entry encountered during a set operation* with an entry for the specified key. The value passed in* the value parameter is stored in the entry, whether or not* an entry already exists for the specified key.** As a side effect, this method expunges all stale entries in the* "run" containing the stale entry. (A run is a sequence of entries* between two null slots.)** @param key the key* @param value the value to be associated with key* @param staleSlot index of the first stale entry encountered while* searching for key.*/private void replaceStaleEntry(ThreadLocal<?> key, Object value, int staleSlot) {Entry[] tab = table;int len = tab.length;Entry e;// Back up to check for prior stale entry in current run.// We clean out whole runs at a time to avoid continual// incremental rehashing due to garbage collector freeing// up refs in bunches (i.e., whenever the collector runs).int slotToExpunge = staleSlot;//每次i-1,直到i-1<0時,i=len-1//跳出遍歷:tab[i]為null//往前找stale元素,直到Entry為nullfor (int i = prevIndex(staleSlot, len); (e = tab[i]) != null;i = prevIndex(i, len)){if (e.get() == null){slotToExpunge = i;}}// Find either the key or trailing null slot of run, whichever// occurs first//往后,直到Entry為nullfor (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相等的e.value = value; //更新valuetab[i] = tab[staleSlot]; //那i的位置是stale元素tab[staleSlot] = e; //把元素放到staleSlot位置// Start expunge at preceding stale entry if it existsif (slotToExpunge == staleSlot){slotToExpunge = i;}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.if (k == null && slotToExpunge == staleSlot){slotToExpunge = i;}}// If key not found, put new entry in stale slottab[staleSlot].value = null;tab[staleSlot] = new Entry(key, value); //放入元素// If there are any other stale entries in run, expunge themif (slotToExpunge != staleSlot){cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);}} }
}
6.ThreadLocalMap.cleanSomeSlots
每次n=n/2來循環調用expungeStaleEntry清理stale數據
public class ThreadLocal<T> {static class ThreadLocalMap {private boolean cleanSomeSlots(int i, int n) {boolean removed = false;Entry[] tab = table;int len = tab.length;do {i = nextIndex(i, len);//從i往后找stale的元素Entry e = tab[i];if (e != null && e.get() == null) {//stale元素n = len;removed = true;i = expungeStaleEntry(i);}} while ( (n >>>= 1) != 0); //從方法的注釋來看,每次對n/2是為了在清除無用數據和速 //度之間做個平衡,這樣既清理了無用數據,又不會因為清理 //太多無用數據,耽誤了插入數據的時間return removed;}}
}
7.ThreadLocalMap.getEntry
public class ThreadLocal<T> {static class ThreadLocalMap {private Entry getEntry(ThreadLocal<?> key) {int i = key.threadLocalHashCode & (table.length - 1);Entry e = table[i];// Android-changed: Use refersTo()if (e != null && e.refersTo(key)){//i這個位置剛好放的Entry的key一致return e;} else {return getEntryAfterMiss(key, i, e);}}}
}
getEntryAfterMiss
?往后遍歷,直到Entry為null
- 如果key相等,返回Entry;
- 如果key為null,是stale元素,清理一下;
- 最終沒找到,就返回null;
public class ThreadLocal<T> {static class ThreadLocalMap {private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {Entry[] tab = table;int len = tab.length;while (e != null) {// Android-changed: Use refersTo()if (e.refersTo(key)){ //key相等return e;}if (e.refersTo(null)){expungeStaleEntry(i); //清理} else{i = nextIndex(i, len); //下一個索引}e = tab[i];}return null;}}
}
8.ThreadLocalMap構造方法
初始化數組table,初始容量為16;
計算index,在table[index]處放入new Entry(key, value);
更新threshold為10;
public class ThreadLocal<T> {static class ThreadLocalMap {/*** 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 initial capacity -- MUST be a power of two.*/private static final int INITIAL_CAPACITY = 16;/*** The next size value at which to resize.*/private int threshold; // Default to 0/*** 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]; //默認數組容量大小為16int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); //計算indextable[i] = new Entry(firstKey, firstValue);//放入數組size = 1; //更新sizesetThreshold(INITIAL_CAPACITY); //設置threshold 16*2/3 = 10}/*** Set the resize threshold to maintain at worst a 2/3 load factor.*/private void setThreshold(int len) {threshold = len * 2 / 3;}}
}