ThreadLocal缺點(diǎn)及解決方法

在前面的一篇文章曾經(jīng)介紹過ThreadLocal,大體知道了ThreadLocal的應(yīng)用場景和實(shí)現(xiàn)原理。

簡單的一句話總結(jié)是每個Thread上都有一個threadLocals屬性,它是一個ThreadLocalMap,里面存放著一個Entry數(shù)組,key是ThreadLocal類型的弱引用,value是對用的值。所有的操作都是基于這個ThreadLocalMap操作的。

但是它有一個局限性,就是不能在父子線程之間傳遞。 即在子線程中無法訪問在父線程中設(shè)置的本地線程變量。 后來為了解決這個問題,引入了一個新的類InheritableThreadLocal。

使用該方法后,子線程可以訪問在創(chuàng)建子線程時父線程當(dāng)時的本地線程變量,其實(shí)現(xiàn)原理就是在父線程創(chuàng)建子線程時將父線程當(dāng)前存在的本地線程變量拷貝到子線程的本地線程變量中。

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
    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);
    }
}

從上面的結(jié)構(gòu)中可以看出,它主要是重寫了getMap、createMap方法。

Thread類中有兩個重要的變量

    ThreadLocal.ThreadLocalMap threadLocals = null;
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
# init()方法片段
Thread parent = currentThread(); 
.....
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

子線程時通過在父線程通過調(diào)用new Thread()方法來創(chuàng)建子線程,Thread#init方法在Thread的構(gòu)造方法中被調(diào)用。

主要是先獲取當(dāng)前線程對象,即待創(chuàng)建的線程的父線程
如果父線程的inheritableThreadLocals不為空,并且inheritThreadLocals為true(默認(rèn)為true),則使用父線程的ingerit本地變量的值來創(chuàng)建子線程的inheritableThreadLocals結(jié)構(gòu),即將父線程中的本地變量復(fù)制到子線程中。

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 < len; 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++;
                    }
                }
            }
        }

子線程默認(rèn)拷貝父線程的方式是淺拷貝,如果需要使用深拷貝,如果需要使用深拷貝,需要使用自定義ThreadLocal,繼承InheritThreadLocal并重寫childValue方法。

而它的實(shí)現(xiàn)原理主要是在創(chuàng)建子線程時將父類線程中的本地變量值parent.inheritableThreadLocals復(fù)制到子線程,即復(fù)制的機(jī)會在創(chuàng)建子線程時。

但是它也有一種缺陷,就是在使用線程池的情況下,因?yàn)榫€程池是復(fù)用線程,不會重復(fù)創(chuàng)建,而上述的inheritableThreadLocals是在創(chuàng)建子線程時才會將父線程的值復(fù)制到子線程,但是在線程池中不會重復(fù)創(chuàng)建,所以多次使用后,仍然記錄的是第一次提交任務(wù)時的外部線程的值,造成了數(shù)據(jù)的錯誤。

那如何解決這種現(xiàn)象呢?

只需在用戶線程向線程池提交任務(wù)時復(fù)制父線程的上下文環(huán)境,就可以實(shí)現(xiàn)本地變量在線程池調(diào)用的透傳。 基于這個思想,阿里提出了TransmittableThreadLocal類。
【導(dǎo)入圖片】
在提交任務(wù)時的Runable或者Callable必須封裝成TtlRunable或者TtlCallableTransmittableThreadLocal覆蓋實(shí)現(xiàn)了ThreadLocal的set、get、remove,實(shí)際存儲inheritableThreadLocal值的工作還是inheritableThreadLocal父類完成,TransmittableThreadLocal只是為每個使用它的Thread單獨(dú)記錄一份存儲了哪些TransmittableThreadLocal對象。

public final void set(T value) {
  super.set(value);
  if (null == value) removeValue();
  else addValue();
}

首先它會調(diào)用父類的InheritableThreadLocal的set方法,將value加入到Thread對象的inheritableThreadLocals變量中。
如果value為null,則調(diào)用removeValue()方法,否則調(diào)用addValue方法。

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);
}

調(diào)用addValue方法,會將當(dāng)前ThreadLocal存儲到TransmittableThreadLocal的全局靜態(tài)變量hodler。所有和Thread綁定的所有TransmittableThreadLocal對象都保存在這個holder中,holder只是為了記錄當(dāng)前Thread綁定了哪些TransmittableThreadLocal對象。

下面具體講一下TtlRunable的原理。

private TtlRunnable(@Nonnull Runnable runnable, boolean releaseTtlValueReferenceAfterRun) {
    this.capturedRef = new AtomicReference<Object>(capture());   
    this.runnable = runnable;
    this.releaseTtlValueReferenceAfterRun = releaseTtlValueReferenceAfterRun;
}

先創(chuàng)建Map容器,用來存儲父線程的本地線程變量,鍵為在父線程執(zhí)行過程中的TransmittableLocal線程;將線程中的值存放在里面。默認(rèn)是淺拷貝,需要深拷貝的話,要重寫copyValue方法。

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);                                       
    }
}

TtlRunable是實(shí)現(xiàn)于Runable,所以線程池執(zhí)行的是TtlRunable,但是在TtlRunnable run方法中國會執(zhí)行Runable run方法。

TtlRunable構(gòu)造方法中,調(diào)用了capture()獲取當(dāng)前線程中所有的上下文,并存儲在AtomicReference中。

當(dāng)線程執(zhí)行時,調(diào)用TtlRunable run方法, TtlRunable會從AtomicReference中獲取出調(diào)用線程中的上下文,并把上下文利用replay方法把上下文復(fù)制到當(dāng)前線程,并把上下文備份。

當(dāng)線程執(zhí)行完,調(diào)用restore把備份的上下文傳入,恢復(fù)備份的上下文傳入,把后面新增的上下文刪除,并重新把上下文復(fù)制到當(dāng)前線程。本次執(zhí)行并不會污染線程池中線程原先的上下文環(huán)境。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容