ThreadLocal

ThreadLocal是什么

ThreadLocal是一個(gè)本地線程副本變量工具類。主要用于將私有線程和該線程存放的副本對(duì)象做一個(gè)映射,各個(gè)線程之間的變量互不干擾,在高并發(fā)場(chǎng)景下,可以實(shí)現(xiàn)無(wú)狀態(tài)的調(diào)用,特別適用于各個(gè)線程依賴不通的變量值完成操作的場(chǎng)景。

從數(shù)據(jù)結(jié)構(gòu)入手

下圖為ThreadLocal的內(nèi)部結(jié)構(gòu)圖

image

從上面的結(jié)構(gòu)圖,我們已經(jīng)窺見ThreadLocal的核心機(jī)制:

  • 每個(gè)Thread線程內(nèi)部都有一個(gè)Map。
  • Map里面存儲(chǔ)線程本地對(duì)象(key)和線程的變量副本(value)
  • 但是,Thread內(nèi)部的Map是由ThreadLocal維護(hù)的,由ThreadLocal負(fù)責(zé)向map獲取和設(shè)置線程的變量值。

所以對(duì)于不同的線程,每次獲取副本值時(shí),別的線程并不能獲取到當(dāng)前線程的副本值,形成了副本的隔離,互不干擾。

Thread線程內(nèi)部的Map在類中描述如下:

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

深入解析ThreadLocal

ThreadLocal類提供如下幾個(gè)核心方法:

public T get()
public void set(T value)
public void remove()

  • get()方法用于獲取當(dāng)前線程的副本變量值。
  • set()方法用于保存當(dāng)前線程的副本變量值。
  • initialValue()為當(dāng)前線程初始副本變量值。
  • remove()方法移除當(dāng)前前程的副本變量值。

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)
            return (T)e.value;
    }
    return setInitialValue();
}

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

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

protected T initialValue() {
    return null;
}

步驟:
1.獲取當(dāng)前線程的ThreadLocalMap對(duì)象threadLocals
2.從map中獲取線程存儲(chǔ)的K-V Entry節(jié)點(diǎn)。
3.從Entry節(jié)點(diǎn)獲取存儲(chǔ)的Value副本值返回。
4.map為空的話返回初始值null,即線程變量副本為null,在使用時(shí)需要注意判斷NullPointerException。

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

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

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

步驟:
1.獲取當(dāng)前線程的成員變量map
2.map非空,則重新將ThreadLocal和新的value副本放入到map中。
3.map空,則對(duì)線程的成員變量ThreadLocalMap進(jìn)行初始化創(chuàng)建,并將ThreadLocal和value副本放入map中。

remove()方法

/**
 * Removes the current thread's value for this thread-local
 * variable.  If this thread-local variable is subsequently
 * {@linkplain #get read} by the current thread, its value will be
 * reinitialized by invoking its {@link #initialValue} method,
 * unless its value is {@linkplain #set set} by the current thread
 * in the interim.  This may result in multiple invocations of the
 * <tt>initialValue</tt> method in the current thread.
 *
 * @since 1.5
 */
public void remove() {
 ThreadLocalMap m = getMap(Thread.currentThread());
 if (m != null)
     m.remove(this);
}

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

remove方法比較簡(jiǎn)單,不做贅述。

ThreadLocalMap

ThreadLocalMap是ThreadLocal的內(nèi)部類,沒有實(shí)現(xiàn)Map接口,用獨(dú)立的方式實(shí)現(xiàn)了Map的功能,其內(nèi)部的Entry也獨(dú)立實(shí)現(xiàn)。

image

在ThreadLocalMap中,也是用Entry來保存K-V結(jié)構(gòu)數(shù)據(jù)的。但是Entry中key只能是ThreadLocal對(duì)象,這點(diǎn)被Entry的構(gòu)造方法已經(jīng)限定死了。

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

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

Entry繼承自WeakReference(弱引用,生命周期只能存活到下次GC前),但只有Key是弱引用類型的,Value并非弱引用。

ThreadLocalMap的成員變量:

static class ThreadLocalMap {
    /**
     * The initial capacity -- MUST be a power of two.
     */
    private static final int INITIAL_CAPACITY = 16;

    /**
     * The table, resized as necessary.
     * table.length MUST always be a power of two.
     */
    private Entry[] table;

    /**
     * The number of entries in the table.
     */
    private int size = 0;

    /**
     * The next size value at which to resize.
     */
    private int threshold; // Default to 0
}

Hash沖突怎么解決

和HashMap的最大的不同在于,ThreadLocalMap結(jié)構(gòu)非常簡(jiǎn)單,沒有next引用,也就是說ThreadLocalMap中解決Hash沖突的方式并非鏈表的方式,而是采用線性探測(cè)的方式,所謂線性探測(cè),就是根據(jù)初始key的hashcode值確定元素在table數(shù)組中的位置,如果發(fā)現(xiàn)這個(gè)位置上已經(jīng)有其他key值的元素被占用,則利用固定的算法尋找一定步長(zhǎng)的下個(gè)位置,依次判斷,直至找到能夠存放的位置。

ThreadLocalMap解決Hash沖突的方式就是簡(jiǎn)單的步長(zhǎng)加1或減1,尋找下一個(gè)相鄰的位置。

/**
 * Increment i modulo len.
 */
private static int nextIndex(int i, int len) {
    return ((i + 1 < len) ? i + 1 : 0);
}

/**
 * Decrement i modulo len.
 */
private static int prevIndex(int i, int len) {
    return ((i - 1 >= 0) ? i - 1 : len - 1);
}

顯然ThreadLocalMap采用線性探測(cè)的方式解決Hash沖突的效率很低,如果有大量不同的ThreadLocal對(duì)象放入map中時(shí)發(fā)送沖突,或者發(fā)生二次沖突,則效率很低。

所以這里引出的良好建議是:每個(gè)線程只存一個(gè)變量,這樣的話所有的線程存放到map中的Key都是相同的ThreadLocal,如果一個(gè)線程要保存多個(gè)變量,就需要?jiǎng)?chuàng)建多個(gè)ThreadLocal,多個(gè)ThreadLocal放入Map中時(shí)會(huì)極大的增加Hash沖突的可能。

ThreadLocalMap的問題

由于ThreadLocalMap的key是弱引用,而Value是強(qiáng)引用。這就導(dǎo)致了一個(gè)問題,ThreadLocal在沒有外部對(duì)象強(qiáng)引用時(shí),發(fā)生GC時(shí)弱引用Key會(huì)被回收,而Value不會(huì)回收,如果創(chuàng)建ThreadLocal的線程一直持續(xù)運(yùn)行,那么這個(gè)Entry對(duì)象中的value就有可能一直得不到回收,發(fā)生內(nèi)存泄露。

如何避免泄漏
既然Key是弱引用,那么我們要做的事,就是在調(diào)用ThreadLocal的get()、set()方法時(shí)完成后再調(diào)用remove方法,將Entry節(jié)點(diǎn)和Map的引用關(guān)系移除,這樣整個(gè)Entry對(duì)象在GC Roots分析后就變成不可達(dá)了,下次GC的時(shí)候就可以被回收。

如果使用ThreadLocal的set方法之后,沒有顯示的調(diào)用remove方法,就有可能發(fā)生內(nèi)存泄露,所以養(yǎng)成良好的編程習(xí)慣十分重要,使用完ThreadLocal之后,記得調(diào)用remove方法。

ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
try {
    threadLocal.set(new Session(1, "Misout的博客"));
    // 其它業(yè)務(wù)邏輯
} finally {
    threadLocal.remove();
}

應(yīng)用場(chǎng)景

還記得Hibernate的session獲取場(chǎng)景嗎?

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

//獲取Session
public static Session getCurrentSession(){
    Session session =  threadLocal.get();
    //判斷Session是否為空,如果為空,將創(chuàng)建一個(gè)session,并設(shè)置到本地線程變量中
    try {
        if(session ==null&&!session.isOpen()){
            if(sessionFactory==null){
                rbuildSessionFactory();// 創(chuàng)建Hibernate的SessionFactory
            }else{
                session = sessionFactory.openSession();
            }
        }
        threadLocal.set(session);
    } catch (Exception e) {
        // TODO: handle exception
    }

    return session;
}

為什么?每個(gè)線程訪問數(shù)據(jù)庫(kù)都應(yīng)當(dāng)是一個(gè)獨(dú)立的Session會(huì)話,如果多個(gè)線程共享同一個(gè)Session會(huì)話,有可能其他線程關(guān)閉連接了,當(dāng)前線程再執(zhí)行提交時(shí)就會(huì)出現(xiàn)會(huì)話已關(guān)閉的異常,導(dǎo)致系統(tǒng)異常。此方式能避免線程爭(zhēng)搶Session,提高并發(fā)下的安全性。

使用ThreadLocal的典型場(chǎng)景正如上面的數(shù)據(jù)庫(kù)連接管理,線程會(huì)話管理等場(chǎng)景,只適用于獨(dú)立變量副本的情況,如果變量為全局共享的,則不適用在高并發(fā)下使用。

總結(jié)

  • 每個(gè)ThreadLocal只能保存一個(gè)變量副本,如果想要上線一個(gè)線程能夠保存多個(gè)副本以上,就需要?jiǎng)?chuàng)建多個(gè)ThreadLocal。
  • ThreadLocal內(nèi)部的ThreadLocalMap鍵為弱引用,會(huì)有內(nèi)存泄漏的風(fēng)險(xiǎn)。
  • 適用于無(wú)狀態(tài),副本變量獨(dú)立后不影響業(yè)務(wù)邏輯的高并發(fā)場(chǎng)景。如果如果業(yè)務(wù)邏輯強(qiáng)依賴于副本變量,則不適合用ThreadLocal解決,需要另尋解決方案。
?著作權(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)容