淺談ThreaLocal類

ThreadLocal是什么?

話不多說(shuō),首先直接給上JDK的解釋:

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its {@code get} or {@code set} method) has its own, independently initialized copy of the variable. {@code ThreadLocal} instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

簡(jiǎn)單翻譯一下,ThreadLocal類用于提供線程局部變量,這些變量與普通的變量不同之處在于每個(gè)線程訪問(wèn)該變量的時(shí)候都有各自獨(dú)立的變量副本,通常是用于希望將狀態(tài)跟線程相關(guān)聯(lián)的一些場(chǎng)景。

ThreadLocal怎么用?

如果單憑上述的解釋還覺(jué)得比較抽象的話,那么我們就寫(xiě)一段代碼看看具體是啥效果:

public class Client {
    private static ThreadLocal<String> localStr = new ThreadLocal<String>(){
        @Override
        protected String initialValue(){
            return "initial localStr value!";
        }
    };
//    也可以使用如下方法給ThreadLocal變量提供初始值
//    private static ThreadLocal<String> localStr = ThreadLocal.withInitial(() -> "initial localStr value!");

    public static void main(String[] args) {
        Thread[] threads = new Thread[5];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " before set :" + localStr.get());
                    localStr.set(Thread.currentThread().getName());
                    System.out.println(Thread.currentThread().getName() + " after set :" + localStr.get());
                }
            }, "Thread-"+i);
        }

        for (Thread t : threads){
            t.start();
        }
    }
}

輸出結(jié)果:

Thread-0 before set :initial localStr value!
Thread-0 after set :Thread-0
Thread-1 before set :initial localStr value!
Thread-1 after set :Thread-1
Thread-2 before set :initial localStr value!
Thread-2 after set :Thread-2
Thread-3 before set :initial localStr value!
Thread-3 after set :Thread-3
Thread-4 before set :initial localStr value!
Thread-4 after set :Thread-4

從代碼和輸出結(jié)果可以看出,localStr這個(gè)靜態(tài)變量在每個(gè)thread當(dāng)中都是互相獨(dú)立的,也就是說(shuō)對(duì)這個(gè)變量進(jìn)行多線程操作是線程安全的,我們不需要對(duì)其進(jìn)行鎖操作。

ThreadLocal怎么實(shí)現(xiàn)的?

知道了ThreadLocal類怎么使用,那我們就會(huì)想它是怎么實(shí)現(xiàn)這種效果的,或者說(shuō)是通過(guò)什么辦法將變量副本跟Thread對(duì)象進(jìn)行了關(guān)聯(lián),下面我們看下ThreadLocal類的幾個(gè)主要方法和靜態(tài)內(nèi)部類(上傳了下截圖發(fā)現(xiàn)好大,不知道怎么調(diào)整大小,就此作罷):

  • 靜態(tài)內(nèi)部類 static class ThreadLocalMap{}
  • public T get()
  • public void set(T value)
  • public void remove()

對(duì)應(yīng)方法實(shí)現(xiàn)如下:

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

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

我們可以看到三個(gè)方法里面都有一個(gè)getMap方法,傳入的參數(shù)是當(dāng)前線程對(duì)象,返回的是當(dāng)前線程所關(guān)聯(lián)的ThreadLocalMap對(duì)象,具體看getMap方法和Thread類的代碼:

ThreadLocalMap getMap(Thread t) {
   return t.threadLocals;
}

簡(jiǎn)單到不能再簡(jiǎn)單的一段代碼有木有,threadLocals這個(gè)玩意兒是Thread類的一個(gè)成員變量。所以getMap方法返回的就是Thread對(duì)象的一個(gè)成員變量,所以不同Thread都有各自的一份ThreadLocalMap。好,到目前為止,我們終于發(fā)現(xiàn)了,原來(lái)真正存儲(chǔ)變量副本的地方是在ThreadLocal類里面的一個(gè)靜態(tài)內(nèi)部類ThreadLocalMap當(dāng)中。
那我們?cè)倮^續(xù)看ThreadLocalMap類是怎么把變量值存放起來(lái)的:

static class Entry extends WeakReference<ThreadLocal<?>> {
    /** The value associated with this ThreadLocal. */
    Object value;

    Entry(ThreadLocal<?> k, Object v) {
        super(k);
        value = v;
    }
}

ThreadLocalMap當(dāng)中又定義了一個(gè)靜態(tài)內(nèi)部類Entry來(lái)存放具體的數(shù)據(jù),這是個(gè)key,value結(jié)構(gòu)的,真正存儲(chǔ)變量副本的地方是Entry里面的value。由于Entry繼承了WeakReference<ThreadLocal<?>>(思考一下這里為什么要用弱引用呢?),因此ThreadLocalMap當(dāng)中的這個(gè)key是用的弱引用,這樣設(shè)計(jì)的目的是當(dāng)內(nèi)存空間不足的時(shí)候,key會(huì)被GC回收掉。

那是不是說(shuō)有了這個(gè)弱引用,ThreadLocalMap就不會(huì)發(fā)生內(nèi)存泄漏了呢?不是的,下面讓我們來(lái)理一理上面第二部分給出的那段代碼的內(nèi)存使用示意圖(簡(jiǎn)單起見(jiàn),這里假設(shè)代碼里只創(chuàng)建了一個(gè)線程):


這里借用參考文章1當(dāng)中的圖

這里假設(shè)我將ThreadLocalRef = null,也就是把ThreadLocalRef指向ThreadLocal的強(qiáng)引用(Strong Reference)打斷,由于Key指向的的ThreadLocal是弱引用,因此當(dāng)內(nèi)存空間不足時(shí),ThreadLocal就會(huì)被GC回收掉Key就指向了null,也就是說(shuō)這個(gè)Entry里的value永遠(yuǎn)沒(méi)人能夠訪問(wèn)到,同時(shí)由于保持著Current Thread Ref -> Current Thread -> Map -> Entry的強(qiáng)引用鏈,因此value的數(shù)據(jù)不會(huì)被GC回收,這就造成了內(nèi)存泄漏問(wèn)題。

有人會(huì)說(shuō),當(dāng)thread對(duì)象被GC回收時(shí),Current Thread Ref -> Current Thread 的強(qiáng)引用鏈不就斷了嗎,這下Heap里面的那坨東西總會(huì)被回收了吧?
是的,沒(méi)錯(cuò)。不過(guò)一般框架底層都會(huì)使用線程池來(lái)創(chuàng)建和管理線程,這時(shí)候線程用完是回到線程池當(dāng)中進(jìn)行復(fù)用的,并不會(huì)直接銷毀,這時(shí)候就會(huì)內(nèi)存泄漏。

好在,ThreadLocalMap的設(shè)計(jì)者已經(jīng)考慮到這種情況,也加上了一些防護(hù)措施:在ThreadLocal的get(),set(),remove()的時(shí)候都會(huì)清除線程ThreadLocalMap里所有key為null的value。這些被動(dòng)預(yù)防措施只是降低了內(nèi)存泄漏的風(fēng)險(xiǎn),但并不能夠保證,因此需要我們?cè)谑褂卯?dāng)中特別注意,在使用完ThreadLocal對(duì)象后,一定要調(diào)用remove()!。

講到這里差不多講完了,那么最后可以再看看下面的代碼,想想輸出結(jié)果是什么?

public class Client {
    private static final ClassA a = new ClassA();
    private static ThreadLocal<ClassA> local = new ThreadLocal<ClassA>();

    public static void main(String[] args) {
        Thread[] threads = new Thread[5];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    local.set(a);
                    local.get().setNum(local.get().getNum() + 5);
                    System.out.println(Thread.currentThread().getName() + " after set :" + local.get().getNum());
                }
            }, "Thread-"+i);
        }

        for (Thread t : threads){
            t.start();
        }
    }
}

class ClassA{
    private int num;

    int getNum() {
        return num;
    }

    void setNum(int num) {
        this.num = num;
    }
}

參考文章:
http://www.importnew.com/22039.html
https://www.toutiao.com/a6586218943701058061

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

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

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