ThreadLocal<T>

ThreadLocal<>適用于什么場(chǎng)景?

  1. 每個(gè)線程都有自己的拷貝實(shí)例,其他線程不能訪問。
  2. 方便在線程內(nèi)部傳遞。
    其實(shí)可以在線程內(nèi)部new一個(gè)對(duì)象來實(shí)現(xiàn)這個(gè)需求,但是這樣會(huì)產(chǎn)生大量的樣板代碼,這樣ThreadLocal就應(yīng)運(yùn)而生了。

怎么用?來個(gè)栗子

public class SessionHandler {
    private static ThreadLocal<Session> threadLocal = ThreadLocal.withInitial(() -> null);
    private static ThreadLocal<Session> another = new ThreadLocal() {
        protected Session initialValue() {
            return null;
        }
    };

    public Session get() {
        return threadLocal.get();
    }

    public void set(Session session) {
        threadLocal.set(session);
    }

    public void remove() {
        threadLocal.remove();
    }
}

原理是什么?需要游向代碼深水區(qū)一探究竟。

public class ThreadLocal<T> {
    protected T initialValue() {
        return null;
    }    


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

    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    } 

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }    


    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 class Thread implements Runnable {
    ThreadLocal.ThreadLocalMap threadLocals = null;
}

原來Thread內(nèi)部有一個(gè)成員ThreadLocal.ThreadLocalMap threadLocals,所以每個(gè)線程都有自己的map,這樣就不會(huì)沖突。這個(gè)map類似HashMap,本質(zhì)是一個(gè)Entry[],key和value都存儲(chǔ)在Entry里,key是ThreadLocal,value是泛型。這個(gè)map不會(huì)發(fā)生哈希碰撞。
為什么要構(gòu)建一個(gè)map,因?yàn)閠hread可能需要多個(gè)threadLocal,那這些threadLocal會(huì)沖突嗎?
還有會(huì)造成內(nèi)存泄露嗎?

參考:ThreadLocal和ThreadLocalMap源碼分析

最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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