Java中的筆試和麪試3---ThreadLocal-面試必問深度解析

ThreadLocal是什麼

ThreadLocal是一個本地線程副本變量工具類。主要用於將私有線程和該線程存放的副本對象做一個映射,各個線程之間的變量互不干擾,在高併發場景下,可以實現無狀態的調用,特別適用於各個線程依賴不同的變量值完成操作的場景。

從數據結構入手

下圖爲ThreadLocal的內部結構圖

ThreadLocal結構內部

從上面的結構圖,我們已經窺見ThreadLocal的核心機制:

  • 每個Thread線程內部都有一個Map。
  • Map裏面存儲線程本地對象(key)和線程的變量副本(value)
  • 但是,Thread內部的Map是由ThreadLocal維護的,由ThreadLocal負責向map獲取和設置線程的變量值。

所以對於不同的線程,每次獲取副本值時,別的線程並不能獲取到當前線程的副本值,形成了副本的隔離,互不干擾。

Thread線程內部的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類提供如下幾個核心方法:

 

public T get()
public void set(T value)
public void remove()
  • get()方法用於獲取當前線程的副本變量值。
  • set()方法用於保存當前線程的副本變量值。
  • initialValue()爲當前線程初始副本變量值。
  • remove()方法移除當前線程的副本變量值。

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.獲取當前線程的ThreadLocalMap對象threadLocals
2.從map中獲取線程存儲的K-V Entry節點。
3.從Entry節點獲取存儲的Value副本值返回。
4.map爲空的話返回初始值null,即線程變量副本爲null,在使用時需要注意判斷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.獲取當前線程的成員變量map
2.map非空,則重新將ThreadLocal和新的value副本放入到map中。
3.map空,則對線程的成員變量ThreadLocalMap進行初始化創建,並將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方法比較簡單,不做贅述。

ThreadLocalMap

ThreadLocalMap是ThreadLocal的內部類,沒有實現Map接口,用獨立的方式實現了Map的功能,其內部的Entry也獨立實現。

ThreadLocalMap類圖

 

在ThreadLocalMap中,也是用Entry來保存K-V結構數據的。但是Entry中key只能是ThreadLocal對象,這點被Entry的構造方法已經限定死了。

 

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結構非常簡單,沒有next引用,也就是說ThreadLocalMap中解決Hash衝突的方式並非鏈表的方式,而是採用線性探測的方式,所謂線性探測,就是根據初始key的hashcode值確定元素在table數組中的位置,如果發現這個位置上已經有其他key值的元素被佔用,則利用固定的算法尋找一定步長的下個位置,依次判斷,直至找到能夠存放的位置。

ThreadLocalMap解決Hash衝突的方式就是簡單的步長加1或減1,尋找下一個相鄰的位置。

 

/**
 * 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採用線性探測的方式解決Hash衝突的效率很低,如果有大量不同的ThreadLocal對象放入map中時發送衝突,或者發生二次衝突,則效率很低。

所以這裏引出的良好建議是:每個線程只存一個變量,這樣的話所有的線程存放到map中的Key都是相同的ThreadLocal,如果一個線程要保存多個變量,就需要創建多個ThreadLocal,多個ThreadLocal放入Map中時會極大的增加Hash衝突的可能。

ThreadLocalMap的問題

由於ThreadLocalMap的key是弱引用,而Value是強引用。這就導致了一個問題,ThreadLocal在沒有外部對象強引用時,發生GC時弱引用Key會被回收,而Value不會回收,如果創建ThreadLocal的線程一直持續運行,那麼這個Entry對象中的value就有可能一直得不到回收,發生內存泄露。

如何避免泄漏
既然Key是弱引用,那麼我們要做的事,就是在調用ThreadLocal的get()、set()方法時完成後再調用remove方法,將Entry節點和Map的引用關係移除,這樣整個Entry對象在GC Roots分析後就變成不可達了,下次GC的時候就可以被回收。

如果使用ThreadLocal的set方法之後,沒有顯示的調用remove方法,就有可能發生內存泄露,所以養成良好的編程習慣十分重要,使用完ThreadLocal之後,記得調用remove方法。

 

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

應用場景

還記得Hibernate的session獲取場景嗎?

 

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

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

    return session;
}

爲什麼?每個線程訪問數據庫都應當是一個獨立的Session會話,如果多個線程共享同一個Session會話,有可能其他線程關閉連接了,當前線程再執行提交時就會出現會話已關閉的異常,導致系統異常。此方式能避免線程爭搶Session,提高併發下的安全性。

使用ThreadLocal的典型場景正如上面的數據庫連接管理,線程會話管理等場景,只適用於獨立變量副本的情況,如果變量爲全局共享的,則不適用在高併發下使用。

總結

  • 每個ThreadLocal只能保存一個變量副本,如果想要上線一個線程能夠保存多個副本以上,就需要創建多個ThreadLocal。
  • ThreadLocal內部的ThreadLocalMap鍵爲弱引用,會有內存泄漏的風險。
  • 適用於無狀態,副本變量獨立後不影響業務邏輯的高併發場景。如果如果業務邏輯強依賴於副本變量,則不適合用ThreadLocal解決,需要另尋解決方案。

推薦閱讀

推薦一款在線畫圖工具

Processon在線畫圖工具,一款很好用的畫圖工具

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章