談?wù)勀莻€(gè)聽起來挺高大上的ThreadLocal

ThreadLocal估計(jì)很多人都沒聽過,因?yàn)檎f實(shí)話平時(shí)寫代碼很少用到,我第一次看到代碼里用ThreadLocal是在Looper的源碼,Looper的源碼中有下面這樣的一個(gè)定義:

    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

定義

大家可以百度看,都說的很高大上,普通的解釋是:當(dāng)使用ThreadLocal維護(hù)變量時(shí),ThreadLocal為每個(gè)使用該變量的線程提供獨(dú)立的變量副本,所以每一個(gè)線程都可以獨(dú)立地改變自己的副本,而不會(huì)影響其它線程所對應(yīng)的副本。

看完了感覺沒看一樣, 要想了解它其實(shí)去看他的源碼一看便知,因?yàn)?code>ThreadLocal代碼也就幾百行而已.

ThreadLocal類主要提供set與get方法, 我們一起來看看get與set是如何與線程關(guān)聯(lián)起來的.

普通的大家想把一個(gè)類與線程關(guān)聯(lián)起來,我們會(huì)采用線程號作為ID,該數(shù)據(jù)作為value,可以存進(jìn)一個(gè)線程安全的map里.但是ThreadLocal不是這么干的.

ThreadLocal

我們開啟源碼模式,JDK6與JDK7實(shí)現(xiàn)有些區(qū)別,不過思想是一樣的.這邊使用JDK7的源碼

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

我們看到,我們存儲(chǔ)的數(shù)據(jù)就被map這個(gè)變量set進(jìn)去了.

那么map來自于以下代碼.

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

        /**
     * 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
     * @param map the map to store.
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

大家發(fā)現(xiàn)了,這個(gè)map竟然是Thread這個(gè)類的一個(gè)變量,初始時(shí)為空,拿不到map會(huì)自動(dòng)給它創(chuàng)建一個(gè)map.

ThreadLocalMap

可以再看看,這個(gè)ThreadLocalMap類:

    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 initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

                /**
         * 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.

            ...
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

常看源碼的同學(xué)會(huì)發(fā)現(xiàn)了,這個(gè)類沒有實(shí)現(xiàn)Map的接口,但是有相似的設(shè)計(jì),我們看到了INITIAL_CAPACITY,看到了Entry這些在HashMap源碼中常見的命名方式,我們還看到了set方法中rehash這個(gè)重新hash的方法,那么總體而言,我們可以把這個(gè)類當(dāng)做這個(gè)是一個(gè)K為ThreadLocal的map.

總結(jié)

知道上面兩點(diǎn)后,我們知道了.Thread這個(gè)線程類中含有一個(gè)ThreadLocalMap變量,我們的ThreadLocal只是幫助你存對象的,真正你使用ThreadLocal存儲(chǔ)一個(gè)與線程相關(guān)的對象時(shí),其實(shí)這個(gè)對象已經(jīng)交給了這個(gè)線程.

什么 還不相信? 那我們看Thread類的代碼:

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

好了,的確Thread類有這么一個(gè)變量.

再看定義: 每一個(gè)線程都可以獨(dú)立地改變自己的副本,而不會(huì)影響其它線程所對應(yīng)的副本。

這次都該明白了,就是每個(gè)Thread都存儲(chǔ)著自己的局部變量,當(dāng)然不會(huì)影響另一個(gè)Thread的threadLocals變量拉.

因此我們可以使用ThreadLocal,來存儲(chǔ)與線程綁定的數(shù)據(jù).我們必須記住,ThreadLocal存儲(chǔ)的變量是屬于每個(gè)線程的,并不是表面上看起來只有一個(gè).

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

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

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