ThreadLocal 原理

ThreadLocal是什麼

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

從數據結構入手

下圖爲ThreadLocal的內部結構圖java

 
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中。session

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在線畫圖工具,一款很好用的畫圖工具

做者:Misout 連接:https://www.jianshu.com/p/98b68c97df9b 來源:簡書 簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。
相關文章
相關標籤/搜索