ThreadLocal詳解
ThreadLocal平常用的還是挺多的,但是對於內部實現一直沒有仔細瞭解過,這幾天在寫一個工程的時候,用到了ThreadLocal保存上下文,突然想到了ThreadLocal一些實現細節上的問題,看了下,同時以此記錄一下,原本想到直接就寫ThreadLocal,但是看了ThreadLocal源碼發現有很多地方需要單獨說下,比如ThreadLocal的尋址方式,ThreadLocal內存泄露等等,而關於尋址方式,ThreadLocal的尋址方式爲開放尋址法,和HashMap的數組加鏈表方式並不相同,而對於解決hash碰撞衝突,有好多種解決方法,因此對於尋址方式,單獨寫一篇文章用以記載,現在就把剩下的詳細講講,此處並不限於只講源碼,還有用途,設計等等。
源碼詳解
首先寫個最簡單的用法,如下:
private static ThreadLocal<Context> ctxMap;
static {
ctxMap = new ThreadLocal<>();
}
public static void set(Context ctx) {
ctxMap.set(ctx);
}
public static Context get() {
return ctxMap.get();
}
寫了一段樣例,最簡單的實例化ThreadLocal對象,同時實現get、set方法,現在就從實例化ThreadLocal開始,進ThreadLocal看看。
/**
* Creates a thread local variable.
* @see #withInitial(java.util.function.Supplier)
*/
public ThreadLocal() {
}
是一個空的構造方法,這裏一般都是適用於在請求初始時就需要對當前上下文進行set操作,要不然後面get操作很有可能就會出現空指針的情況,所以一般使用方法爲在初始化時進行init操作,如下:
ctxMap = new ThreadLocal<Object>() {
@Override
protected Object initialValue() {
return new Object();
}
}
這樣可以保證即使是沒有set的情況下,也能拿到特定特徵數據,從而進行其他邏輯操作。
接下來我們看ThreadLocal中的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);
}
set中的操作比較簡單,獲取當前線程,根據當前線程獲取ThreadLocalMap對象,然後當前ThreadLocalMap對象如果存在則保存value,如果不存在則創建ThreadLocalMap對象,簡單的看下getMap方法。
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
就是返回當前線程的threadLocals對象,這裏不做深究,後面還會再講,接着繼續看之前的代碼,看set中的createMap操作,如下:
/**
* Create the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the map
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
和預料的差不多,就是給當前threadLocals對象進行實例化操作,這裏我們不妨看下ThreadLocalMap的結構,直接進入ThreadLocalMap的構造方法。
/**
* 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];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
這裏操作沒有太多可以講述的,就是實例化, table數組大小爲16,同時設置閾值。
我們回到map的set操作,進入set方法源碼。
/**
* 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);
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();
}
根據key算出i座標值後,然後獲取當前索引下是否有值,如果當前槽點有值,並且當前槽點下key和當前傳入的key相同,則直接進行value替換,如果當前槽點key爲null,但是存在值,則進行槽點值替換操作,這個就是替換內存泄露的數據,這個需要講述的比較多,分爲兩篇,這個在後面單獨講述,這裏還是講get、set、remove等操作的源碼。
上述三種情況,一種是當該槽點的key就是當前要保存的key時,直接進行value替換。另外一種是如果value不爲空,但是key爲空,則進行替換,這個在下一篇中單獨講,第三種情況就是該節點不爲空,此時就使用了線性探測法向下尋找下一個可用節點,此時如果尋找到一個可用節點,則進行新Entry插入操作,此時並且檢測當前佔滿槽點已經超過閾值,則進行擴容操作,可以進入rehash方法看看擴容如何實現。
/**
* Re-pack and/or re-size the table. First scan the entire
* table removing stale entries. If this doesn't sufficiently
* shrink the size of the table, double the table size.
*/
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
這裏將expungeStaleEntries()方法放到下一節中再進行講述,直說resize方法。這裏當使用節點數大於當前總數的3/4時,便進行擴容操作,這裏3/4容量就是一個經驗值,在前人經過反覆試驗以後,發現使用容量在3/4時擴容碰撞次數較少。
這裏進入resize()方法。
/**
* 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);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
resize方法倒是挺簡單,就是新建table,容量爲當前的2倍,然後進行kv的替換。
現在回頭看看get方法和remove方法,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) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
get操作比較簡單,就是從當前map中取出當前key對應的value即可,估計revome操作也是類似,一起來看下。
/**
* 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);
}
操作還是比較簡單,就是獲取map,然後remove當前對象。
ThreadLocal這些方法還是比較簡單,但是這裏得單獨講講ThreadLocal處理髒key的辦法,這個放在下一節來講。