ThreadLocal 深度解析

一.對ThreadLocal的理解 二.深刻解析ThreadLocal類 三.ThreadLocal的應用場景算法

對ThreadLocal的理解

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

咱們先寫一個例子編程

class ConnectionManager {
     
    private static Connection connect = null;
     
    public static Connection openConnection() {
        if(connect == null){
            connect = DriverManager.getConnection();
        }
        return connect;
    }
     
    public static void closeConnection() {
        if(connect!=null)
            connect.close();
    }
}
複製代碼

假設有這樣一個數據庫連接管理類,這段代碼在單線程中使用是沒有任何問題的,可是若是在多線程中使用呢?很顯然,在多線程中使用會存在線程安全問題:第一,這裏面的2個方法都沒有進行同步,極可能在openConnection方法中會屢次建立connect;第二,因爲connect是共享變量,那麼必然在調用connect的地方須要使用到同步來保障線程安全,由於極可能一個線程在使用connect進行數據庫操做,而另一個線程調用closeConnection關閉連接。數組

因此出於線程安全的考慮,必須將這段代碼的兩個方法進行同步處理,而且在調用connect的地方須要進行同步處理。安全

這樣將會大大影響程序執行效率,由於一個線程在使用connect進行數據庫操做的時候,其餘線程只有等待。bash

那麼你們來仔細分析一下這個問題,這地方到底需不須要將connect變量進行共享?事實上,是不須要的。假如每一個線程中都有一個connect變量,各個線程之間對connect變量的訪問其實是沒有依賴關係的,即一個線程不須要關心其餘線程是否對這個connect進行了修改的。服務器

到這裏,可能會有朋友想到,既然不須要在線程之間共享這個變量,能夠直接這樣處理,在每一個須要使用數據庫鏈接的方法中具體使用時才建立數據庫連接,而後在方法調用完畢再釋放這個鏈接。好比下面這樣:session

class ConnectionManager {
     
    private  Connection connect = null;
     
    public Connection openConnection() {
        if(connect == null){
            connect = DriverManager.getConnection();
        }
        return connect;
    }
     
    public void closeConnection() {
        if(connect!=null)
            connect.close();
    }
}
 
 
class Dao{
    public void insert() {
        ConnectionManager connectionManager = new ConnectionManager();
        Connection connection = connectionManager.openConnection();
         
        //使用connection進行操做
         
        connectionManager.closeConnection();
    }
}
複製代碼

這樣處理確實也沒有任何問題,因爲每次都是在方法內部建立的鏈接,那麼線程之間天然不存在線程安全問題。因爲在方法中須要頻繁地開啓和關閉數據庫鏈接,這樣會致使服務器壓力很是大,嚴重影響程序執行性能。多線程

這種狀況下咱們可使用ThreadLocal,由於ThreadLocal在每一個線程中對該變量會建立一個副本,即每一個線程內部都會有一個該變量,且在線程內部任何地方均可以使用,線程之間互不影響,這樣一來就不存在線程安全問題,也不會嚴重影響程序執行性能。併發

可是要注意,雖然ThreadLocal可以解決上面說的問題,可是因爲在每一個線程中都建立了副本,因此要考慮它對資源的消耗,好比內存的佔用會比不使用ThreadLocal要大。

下圖爲ThreadLocal的內部結構圖

image

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

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

因此對於不一樣的線程,每次獲取副本值時,別的線程並不能獲取到當前線程的副本值,造成了副本的隔離,互不干擾。

.深刻解析ThreadLocal類

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類提供以下幾個核心方法:

public T get() { }
public void set(T value) { }
public void remove() { }
protected T initialValue() { }
複製代碼
  • 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();
}
複製代碼

第一句是取得當前線程,而後經過getMap(t)方法獲取到一個map,map的類型爲ThreadLocalMap。而後接着下面獲取到<key,value>鍵值對,注意這裏獲取鍵值對傳進去的是 this,而不是當前線程t。 若是獲取成功,則返回value值。 若是map爲空,則調用setInitialValue方法返回value。 咱們上面的每一句來仔細分析: 首先看一下getMap方法中作了什麼:

ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}
複製代碼

可能你們沒有想到的是,在getMap中,是調用當期線程t,返回當前線程t中的一個成員變量threadLocals。 那麼咱們繼續取Thread類中取看一下成員變量threadLocals是什麼:

ThreadLocal.ThreadLocalMap threadLocals = null;
複製代碼

實際上就是一個ThreadLocalMap,這個類型是ThreadLocal類的一個內部類,咱們繼續取看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;
            }
        }
複製代碼

能夠看到ThreadLocalMap的Entry繼承了WeakReference,而且使用ThreadLocal做爲鍵值。 而後再繼續看setInitialValue方法的具體實現:

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

複製代碼

 若是map不爲空,設置鍵值對爲空,再建立Map,看一下createMap的實現:

/**
     * 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
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
複製代碼

ThreadLocal爲每一個線程建立變量的副本的過程:

首先,在每一個線程Thread內部有一個ThreadLocal.ThreadLocalMap類型的成員變量threadLocals,這個threadLocals就是用來存儲實際的變量副本的,鍵值爲當前ThreadLocal變量,value爲變量副本(即T類型的變量)。

初始時,在Thread裏面,threadLocals爲空,當經過ThreadLocal變量調用get()方法或者set()方法,就會對Thread類中的threadLocals進行初始化,而且以當前ThreadLocal變量爲鍵值,以ThreadLocal要保存的副本變量爲value,存到threadLocals。

而後在當前線程裏面,若是要使用副本變量,就能夠經過get方法在threadLocals裏面查找。

下面經過一個例子來證實經過ThreadLocal能達到在每一個線程中建立變量副本的效果:

public class Test {
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
    ThreadLocal<String> stringLocal = new ThreadLocal<String>();
     
    public void set() {
        longLocal.set(Thread.currentThread().getId());
        stringLocal.set(Thread.currentThread().getName());
    }
     
    public long getLong() {
        return longLocal.get();
    }
     
    public String getString() {
        return stringLocal.get();
    }
     
    public static void main(String[] args) throws InterruptedException {
        final Test test = new Test();
        test.set();
        System.out.println(test.getLong());
        System.out.println(test.getString());
   
        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                System.out.println(test.getLong());
                System.out.println(test.getString());
            };
        };
        thread1.start();
        thread1.join();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
    }
}

複製代碼

輸出結果以下圖

圖片.png

從這段代碼的輸出結果能夠看出,在main線程中和thread1線程中,longLocal保存的副本值和stringLocal保存的副本值都不同。最後一次在main線程再次打印副本值是爲了證實在main線程中和thread1線程中的副本值確實是不一樣的。

總結一下:

1)實際的經過ThreadLocal建立的副本是存儲在每一個線程本身的threadLocals中的; 2)爲什麼threadLocals的類型ThreadLocalMap的鍵值爲ThreadLocal對象,由於每一個線程中可有多個threadLocal變量,就像上面代碼中的longLocal和stringLocal; 3)在進行get以前,必須先set,不然會報空指針異常;

若是想在get以前不須要調用set就能正常訪問的話,必須重寫initialValue()方法。 由於在上面的代碼分析過程當中,咱們發現若是沒有先set的話,即在map中查找不到對應的存儲,則會經過調用setInitialValue方法返回i,而在setInitialValue方法中,有一個語句是T value = initialValue(), 而默認狀況下,initialValue方法返回的是null。

看下面這個例子:

public class Test {
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
    ThreadLocal<String> stringLocal = new ThreadLocal<String>();
 
    public void set() {
        longLocal.set(Thread.currentThread().getId());
        stringLocal.set(Thread.currentThread().getName());
    }
     
    public long getLong() {
        return longLocal.get();
    }
     
    public String getString() {
        return stringLocal.get();
    }
     
    public static void main(String[] args) throws InterruptedException {
        final Test test = new Test();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
 
        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                System.out.println(test.getLong());
                System.out.println(test.getString());
            };
        };
        thread1.start();
        thread1.join();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
    }
}
複製代碼

在main線程中,沒有先set,直接get的話,運行時會報空指針異常。 可是若是改爲下面這段代碼,即重寫了initialValue方法:

public class Test {
    ThreadLocal<Long> longLocal = new ThreadLocal<Long>(){
        protected Long initialValue() {
            return Thread.currentThread().getId();
        };
    };
    ThreadLocal<String> stringLocal = new ThreadLocal<String>(){;
        protected String initialValue() {
            return Thread.currentThread().getName();
        };
    };
     
    public void set() {
        longLocal.set(Thread.currentThread().getId());
        stringLocal.set(Thread.currentThread().getName());
    }
     
    public long getLong() {
        return longLocal.get();
    }
     
    public String getString() {
        return stringLocal.get();
    }
     
    public static void main(String[] args) throws InterruptedException {
        final Test test = new Test();
 
        test.set();
        System.out.println(test.getLong());
        System.out.println(test.getString());
     
         
        Thread thread1 = new Thread(){
            public void run() {
                test.set();
                System.out.println(test.getLong());
                System.out.println(test.getString());
            };
        };
        thread1.start();
        thread1.join();
         
        System.out.println(test.getLong());
        System.out.println(test.getString());
    }
}
複製代碼

就能夠直接不用先set而直接調用get了。

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

複製代碼

set方法過程: 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; } 複製代碼

ThreadLocalMap

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

image

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

複製代碼

三.ThreadLocal的應用場景

最多見的ThreadLocal使用場景爲 用來解決 數據庫鏈接、Session管理等。

private static ThreadLocal<Connection> connectionHolder
= new ThreadLocal<Connection>() {
public Connection initialValue() {
    return DriverManager.getConnection(DB_URL);
}
};
 
public static Connection getConnection() {
return connectionHolder.get();
}
複製代碼
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;
}

複製代碼
private static final ThreadLocal threadSession = new ThreadLocal();
 
public static Session getSession() throws InfrastructureException {
    Session s = (Session) threadSession.get();
    try {
        if (s == null) {
            s = getSessionFactory().openSession();
            threadSession.set(s);
        }
    } catch (HibernateException ex) {
        throw new InfrastructureException(ex);
    }
    return s;
}
複製代碼

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

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

總結

  • 每一個ThreadLocal只能保存一個變量副本,若是想要一個線程可以保存多個副本,就須要建立多個ThreadLocal。
  • ThreadLocal內部的ThreadLocalMap鍵爲弱引用,會有內存泄漏的風險。
  • 適用於無狀態,副本變量獨立後不影響業務邏輯的高併發場景。若是若是業務邏輯強依賴於副本變量,則不適合用ThreadLocal解決,須要另尋解決方案。
相關文章
相關標籤/搜索