Java ThreadLocal

Java-ThreadLocal

參考

用途

誤區

看到很多資料上都有一些誤區: 即使用ThreadLocal是用于解決對象共享訪問問題, 線程安全問題等. 其實不然. 另外也不存在什么對對象的拷貝, 因為實際上和線程相關的參數實際上就存儲在了Thread對象中的ThreadLocalMap threadLocals里面.

正確理解

最先接觸到Thread Local這個概念是使用Python的Flask框架. 該框架中有一個對象g. 文檔: flask.g.
該對象可以直接用from flask import g導入. 然后可以在需要存一些需要在多個地方使用的數據時, 可以g.set(), 然后需要獲取值的時候可以直接g.get(). 而比較神奇的是在多線程環境下, 每個使用到g的地方都是直接這樣引用的, 但是不同線程間的數據卻不會相互覆蓋. 其實g對象的實現就是使用了Thread Local.

所以個人理解, ThreadLocal其實主要是為了方便提供一些可能多個線程都需要訪問的數據, 但是每個線程需要獨享一個這樣的對象. 如果用傳統的全局變量, 每個線程雖然都能訪問到, 但是會發生數據覆蓋的問題, 而使用Thread Local, 則可以很方便地在不傳遞過多參數的情況下實現一個線程對應一個對象實例. 即這個數據需要對很多線程可見(global), 但每個線程其實都擁有一個獨享的該數據對象(local).

如果不使用ThreadLocal想要實現類似的功能, 其實用一個全局靜態Map<Thread, Value>就可以做到. 不過ThreadLocal就是為了簡化這個操作, 而且效率高, 所以直接使用ThreadLocal即可.

一個應用場景(類似flask.g對象):

  • 每個請求由一個線程處理
  • 在請求處理過程中, 有多個地方需要用到某個數據 (比如說before_request, request_handling, post_request這幾個地方)

一個看起來可行的方法是直接在請求處理代碼中設置一個全局變量, 但是這樣不同線程就會讀到/修改同一個全局變量. 這時候使用ThreadLocal就可以很好地避免這個問題, 而不用我們自己去維護一個跟線程有關的Map來根據不同的線程獲取對應的數據.

ThreadLocal例子

TransactionManager類:
注意threadLocal是一個靜態的ThreadLocal變量. 意味著全部的線程訪問的都是同一個ThreadLocal對象.

package multithreading.threadlocal;

/**
 * Created by xiaofu on 17-11-15.
 * https://dzone.com/articles/painless-introduction-javas-threadlocal-storage
 */
public class TransactionManager {

    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    public static void newTransaction(){
        // 生成一個新的transaction id
        String id = "" + System.currentTimeMillis();
        threadLocal.set(id);
    }

    public static void endTransaction(){
        // 避免出現內存泄露問題
        threadLocal.remove();
    }

    public static String getTransactionID(){
        return threadLocal.get();
    }


}

ThreadLocalTest類:

package multithreading.threadlocal;

/**
 * Created by xiaofu on 17-11-15.
 * https://dzone.com/articles/painless-introduction-javas-threadlocal-storage
 */
public class ThreadLocalTest {

    public static class Task implements Runnable{

        private String name;

        public Task(String name){this.name = name;}

        @Override
        public void run() {
            TransactionManager.newTransaction();
            System.out.printf("Task %s transaction id: %s\n", name, TransactionManager.getTransactionID());
            TransactionManager.endTransaction();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        // 在main線程先操作一下TransactionManager
        TransactionManager.newTransaction();
        System.out.println("Main transaction id: " + TransactionManager.getTransactionID());

        String taskName = "[Begin a new transaction]";
        Thread thread = new Thread(new Task(taskName));
        thread.start();
        thread.join();

        System.out.println(String.format("Task %s is done", taskName));
        System.out.println("Main transaction id: " + TransactionManager.getTransactionID());
        TransactionManager.endTransaction();

    }

}

測試結果:
重點在于在main線程調用getTransactionID()的返回值并沒有因為期間有一另個Thread設置了TransactionManger中的ThreadLocal變量的值而改變.

Main transaction id: 1510730858223
Task [Begin a new transaction] transaction id: 1510730858224
Task [Begin a new transaction] is done
Main transaction id: 1510730858223

可以看出不同線程對于同一個ThreadLocal變量的操作是不會有互相影響的. 因為該ThreadLocal變量對于所有線程都是全局的, 但是其存儲的數據卻是和線程相關的.

原理

ThreadLoccal類的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);
    }

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

從上面代碼可以看出Thread類是有一個叫threadLocals的成員的.

public
class Thread implements Runnable{
    // ... 省略 ...
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
    // ... 省略 ...
}

ThreadLocalMapThreadLocal的一個靜態內部類:
以下僅摘了了用于理解ThreadLocal原理的代碼:

/**
     * 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{
    
        /**
         * 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);
                value = v;
            }
        }
        
        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
        

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

所以實際ThreadLocalset方法是將對象存儲到了調用該ThreadLocal的線程對象的threadLocals成員中. 而該成員的類型為ThreadLocalMap. 注意ThreadLocalMapset方法, 其key的類型是任何類型的ThreadLocal對象. 所以ThreadLocalMap對象存儲了ThreadLocal -> value的鍵值對. 因為一個線程可能使用多個ThreadLocal對象, 所以使用了ThreadLocalMap來管理這些值. 這也解釋了ThreadLocalset方法中map.set(this, value);這句代碼的意思.

再來看ThreadLoccal類的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();
    }

其實就是獲取當先的線程, 然后得到其ThreadLocalMap類型的threadLocals對象. 然后傳遞this, 即用于表明當前是要取得threadLocalskey為當前這個ThreadLocal的對象.

關于內存泄露

原因在上面那篇文章說得很清楚了.
接下來說一個關于ThreadLocal.remove()方法的實踐. 雖然有些情況不會造成內存泄露, 我們可以不調用ThreadLocal.remove()方法. 但是這可能會造成一些其他問題, 比如說當線程被線程池重用的時候. 如果線程在使用完ThreadLocal后沒有remove, 那么很可能下次該線程再次執行的時候(可能是不同任務了), 就可能會讀到一個之前設置過的值.

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,836評論 6 540
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,275評論 3 428
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,904評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,633評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,368評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,736評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,740評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,919評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,481評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,235評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,427評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,968評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,656評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,055評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,348評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,160評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,380評論 2 379

推薦閱讀更多精彩內容

  • ThreadLocal提供了線程本地變量,它可以保證訪問到的變量屬于當前線程,每個線程都保存有一個變量副本,每個線...
    FX_SKY閱讀 15,430評論 0 3
  • 概述 ThreadLocal如果單純從名字上來看像是“本地線程"這么個意思,只能說這個名字起的確實不太好,很容易讓...
    eliter0609閱讀 495評論 0 0
  • Android Handler機制系列文章整體內容如下: Android Handler機制1之ThreadAnd...
    隔壁老李頭閱讀 7,662評論 4 30
  • 前言 ThreadLocal很多同學都搞不懂是什么東西,可以用來干嘛。但面試時卻又經常問到,所以這次我和大家一起學...
    liangzzz閱讀 12,482評論 14 228
  • 推薦BGM:一絲不掛 時光總有一天會將我們拆散, 可是即便如此, 我們還是要在一起。 北離很喜歡一個女孩,叫曲婷,...
    黎源大大閱讀 277評論 7 1