1.ThreadLocalMap.Entry
key:指向key的是弱引用
value:强引用
java
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
java
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_INCREMENT
private 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)计算下一个索引,看是否被占用
java
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越界,怎为0
for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get(); //获取key
if (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大于threshold
if (!cleanSomeSlots(i, sz) && sz >= threshold){
rehash(); //扩容
}
}
}
}
4.扩容
- 先清理所有的stale数据;
- 如果size大于等于threshold*3/4,进行扩容;
java
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
java
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为null
expungeStaleEntry(j);
}
}
}
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
tab[staleSlot].value = null; //value设为null
tab[staleSlot] = null; //entry设为null
size--; //size减1
// 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) {//如果元素不为null,但是key为null
e.value = null;
tab[i] = null;
size--;
} else {
//不是stale元素的话,重新将这个元素放到合适的位置
int h = k.threadLocalHashCode & (len - 1); //计算index
if (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的index
h = 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,将该元素放入合适的位置;
java
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); //重新计算index
while (newTab[h] != null){//找到该元素该放的位置
h = nextIndex(h, newLen);
}
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen); //更新threshold
size = count;
table = newTab;
}
}
}
5.ThreadLocalMap.replaceStaleEntry
java
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为null
for (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为null
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相等的
e.value = value; //更新value
tab[i] = tab[staleSlot]; //那i的位置是stale元素
tab[staleSlot] = e; //把元素放到staleSlot位置
// Start expunge at preceding stale entry if it exists
if (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 slot
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value); //放入元素
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot){
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
}
}
}
6.ThreadLocalMap.cleanSomeSlots
每次n=n/2来循环调用expungeStaleEntry清理stale数据
java
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
java
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;
java
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;
java
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]; //默认数组容量大小为16
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); //计算index
table[i] = new Entry(firstKey, firstValue);//放入数组
size = 1; //更新size
setThreshold(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;
}
}
}