每個Thread上都有一個threadLocals屬性,它是一個ThreadLocalMap,裡面存放著一個Entry數組,key是ThreadLocal類型的弱引用,value是對用的值。所有的操作都是基於這個ThreadLocalMap操作的。
但是它有一個侷限性,就是不能在父子線程之間傳遞。 即在子線程中無法訪問在父線程中設置的本地線程變量。 後來為了解決這個問題,引入了一個新的類InheritableThreadLocal。
使用該方法後,子線程可以訪問在創建子線程時父線程當時的本地線程變量,其實現原理就是在父線程創建子線程時將父線程當前存在的本地線程變量拷貝到子線程的本地線程變量中。
<code>public class InheritableThreadLocalextends ThreadLocal /<code>{
protected T childValue(T parentValue) {
return parentValue;
}
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
從上面的結構中可以看出,它主要是重寫了getMap、createMap方法。
Thread類中有兩個重要的變量
<code> ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;/<code>
<code># init()方法片段
Thread parent = currentThread();
.....
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);/<code>
子線程時通過在父線程通過調用new Thread()方法來創建子線程,Thread#init方法在Thread的構造方法中被調用。
主要是先獲取當前線程對象,即待創建的線程的父線程 如果父線程的inheritableThreadLocals不為空,並且inheritThreadLocals為true(默認為true),則使用父線程的ingerit本地變量的值來創建子線程的inheritableThreadLocals結構,即將父線程中的本地變量複製到子線程中。
<code>private Entry[] table;
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<object> key = (ThreadLocal<object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}/<object>/<object>/<code>
子線程默認拷貝父線程的方式是淺拷貝,如果需要使用深拷貝,如果需要使用深拷貝,需要使用自定義ThreadLocal,繼承InheritThreadLocal並重寫childValue方法。
而它的實現原理主要是在創建子線程時將父類線程中的本地變量值parent.inheritableThreadLocals複製到子線程,即複製的機會在創建子線程時。
但是它也有一種缺陷,就是在使用線程池的情況下,因為線程池是複用線程,不會重複創建,而上述的inheritableThreadLocals是在創建子線程時才會將父線程的值複製到子線程,但是在線程池中不會重複創建,所以多次使用後,仍然記錄的是第一次提交任務時的外部線程的值,造成了數據的錯誤。
那如何解決這種現象呢?
只需在用戶線程向線程池提交任務時複製父線程的上下文環境,就可以實現本地變量在線程池調用的透傳。 基於這個思想,阿里提出了TransmittableThreadLocal類。【導入圖片】在提交任務時的Runable或者Callable必須封裝成TtlRunable或者TtlCallable。TransmittableThreadLocal覆蓋實現了ThreadLocal的set、get、remove,實際存儲inheritableThreadLocal值的工作還是inheritableThreadLocal父類完成,TransmittableThreadLocal只是為每個使用它的Thread單獨記錄一份存儲了哪些TransmittableThreadLocal對象。
<code>public final void set(T value) {
super.set(value);
if (null == value) removeValue();
else addValue();
}/<code>
首先它會調用父類的InheritableThreadLocal的set方法,將value加入到Thread對象的inheritableThreadLocals變量中。 如果value為null,則調用removeValue()方法,否則調用addValue方法。
<code>private void addValue() {
if (!holder.get().containsKey(this)) { // @1
holder.get().put(this, null); // WeakHashMap supports null value.
}
}
private void removeValue() {
holder.get().remove(this);
}/<code>
調用addValue方法,會將當前ThreadLocal存儲到TransmittableThreadLocal的全局靜態變量hodler。所有和Thread綁定的所有TransmittableThreadLocal對象都保存在這個holder中,holder只是為了記錄當前Thread綁定了哪些TransmittableThreadLocal對象。
下面具體講一下TtlRunable的原理。
<code>private TtlRunnable(@Nonnull Runnable runnable, boolean releaseTtlValueReferenceAfterRun) {
this.capturedRef = new AtomicReference<object>(capture());
this.runnable = runnable;
this.releaseTtlValueReferenceAfterRun = releaseTtlValueReferenceAfterRun;
}/<object>/<code>
先創建Map容器,用來存儲父線程的本地線程變量,鍵為在父線程執行過程中的TransmittableLocal線程;將線程中的值存放在裡面。默認是淺拷貝,需要深拷貝的話,要重寫copyValue方法。
<code>public void run() {
Object captured = capturedRef.get();
if (captured == null || releaseTtlValueReferenceAfterRun && !capturedRef.compareAndSet(captured, null)) {
throw new IllegalStateException("TTL value reference is released after run!");
}
Object backup = replay(captured);
try {
runnable.run();
} finally {
restore(backup);
}
}/<code>
TtlRunable是實現於Runable,所以線程池執行的是TtlRunable,但是在TtlRunnable run方法中國會執行Runable run方法。
TtlRunable構造方法中,調用了capture()獲取當前線程中所有的上下文,並存儲在AtomicReference中。
當線程執行時,調用TtlRunable run方法, TtlRunable會從AtomicReference中獲取出調用線程中的上下文,並把上下文利用replay方法把上下文複製到當前線程,並把上下文備份。
當線程執行完,調用restore把備份的上下文傳入,恢復備份的上下文傳入,把後面新增的上下文刪除,並重新把上下文複製到當前線程。本次執行並不會汙染線程池中線程原先的上下文環境。
作者:房東的小黑黑
原文鏈接:https://juejin.im/post/5e8d809d51882573cc56b156
閱讀更多 Java小寒 的文章