Spring---------ThreadLocal(線程變量副本)


參考:https://blog.csdn.net/olikeit/article/details/80855823

https://www.jianshu.com/p/98b68c97df9b

Synchronized實現內存共享,ThreadLocal為每個線程維護一個本地變量。
1. 采用空間換時間,它用於線程間的數據隔離,為每一個使用該變量的線程提供一個副本,每個線程都可以獨立地改變自己的副本,而不會和其他線程的副本沖突。
2. ThreadLocal類中維護一個Map,用於存儲每一個線程的變量副本,Map中元素的鍵為線程對象,而值為對應線程的變量副本。
3. 主要用於將私有線程和該線程存放的副本對象做一個映射,各個線程之間的變量互不干擾,在高並發場景下,可以實現無狀態的調用,特別適用於各個線程依賴不通的變量值完成操作的場景。

 

從數據結構入手,先看看ThreadLocal的內部結構圖:

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

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

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

Thread線程內部的Map在類中描述如下:
1 public class Thread implements Runnable {
2     /* ThreadLocal values pertaining to this thread. This map is maintained
3      * by the ThreadLocal class. */
4     ThreadLocal.ThreadLocalMap threadLocals = null;
5 }

ThreadLocal的方法比較簡單,

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

1.get()方法

 1 /**
 2  * Returns the value in the current thread's copy of this
 3  * thread-local variable.  If the variable has no value for the
 4  * current thread, it is first initialized to the value returned
 5  * by an invocation of the {@link #initialValue} method.
 6  *
 7  * @return the current thread's value of this thread-local
 8  */
 9 public T get() {
10     Thread t = Thread.currentThread();
11     ThreadLocalMap map = getMap(t);
12     if (map != null) {
13         ThreadLocalMap.Entry e = map.getEntry(this);
14         if (e != null)
15             return (T)e.value;
16     }
17     return setInitialValue();
18 }
19 
20 ThreadLocalMap getMap(Thread t) {
21     return t.threadLocals;
22 }
23 
24 private T setInitialValue() {
25     T value = initialValue();
26     Thread t = Thread.currentThread();
27     ThreadLocalMap map = getMap(t);
28     if (map != null)
29         map.set(this, value);
30     else
31         createMap(t, value);
32     return value;
33 }
34 
35 protected T initialValue() {
36     return null;
37 }
步驟:
1.獲取當前線程的ThreadLocalMap對象threadLocals
2.從map中獲取線程存儲的K-V Entry節點。
3.從Entry節點獲取存儲的Value副本值返回。
4.map為空的話返回初始值null,即線程變量副本為null,在使用時需要注意判斷NullPointerException。

ThreadLocal進行get的時候,是從當前線程Thread中獲取到有且唯一的ThreadLocalMap對象(Thread的ThreadLocalMap屬性如果為空,也就是說這個線程從來都沒有用過ThreadLocal設置過值,返回null),然后把自己做為鍵去該Map里面找,找到就返回對於的value,沒有就返回null。

2.set()方法
 1 /**
 2  * Sets the current thread's copy of this thread-local variable
 3  * to the specified value.  Most subclasses will have no need to
 4  * override this method, relying solely on the {@link #initialValue}
 5  * method to set the values of thread-locals.
 6  *
 7  * @param value the value to be stored in the current thread's copy of
 8  *        this thread-local.
 9  */
10 public void set(T value) {
11     Thread t = Thread.currentThread();
12     ThreadLocalMap map = getMap(t);
13     if (map != null)
14         map.set(this, value);
15     else
16         createMap(t, value);
17 }
18 
19 ThreadLocalMap getMap(Thread t) {
20     return t.threadLocals;
21 }
22 
23 void createMap(Thread t, T firstValue) {
24     t.threadLocals = new ThreadLocalMap(this, firstValue);
25 }

步驟:
1.獲取當前線程的成員變量map
2.map非空,則重新將ThreadLocal和新的value副本放入到map中。
3.map空,則對線程的成員變量ThreadLocalMap進行初始化創建,並將ThreadLocal和value副本放入map中。

​​​​ThreadLocal進行set的時候,是在當前線程Thread中獲取到有且唯一的ThreadLocalMap對象(如果沒有就新建一個ThreadLocalMap對象設置進Thread的屬性里),

然后把自己作為鍵,value作為值set進這個Map里。

 

3.remove()方法

 1 /**
 2  * Removes the current thread's value for this thread-local
 3  * variable.  If this thread-local variable is subsequently
 4  * {@linkplain #get read} by the current thread, its value will be
 5  * reinitialized by invoking its {@link #initialValue} method,
 6  * unless its value is {@linkplain #set set} by the current thread
 7  * in the interim.  This may result in multiple invocations of the
 8  * <tt>initialValue</tt> method in the current thread.
 9  *
10  * @since 1.5
11  */
12 public void remove() {
13  ThreadLocalMap m = getMap(Thread.currentThread());
14  if (m != null)
15      m.remove(this);
16 }
17 
18 ThreadLocalMap getMap(Thread t) {
19     return t.threadLocals;
20 }

 

ThreadLocal中最重要的部分就是內部的ThreadLocalMap,ThreadLocalMap沒有實現Map接口,用獨立的方式實現了Map功能,其內部的Entry也獨立實現。

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

1 static class Entry extends WeakReference<ThreadLocal> {
2     /** The value associated with this ThreadLocal. */
3     Object value;
4 
5     Entry(ThreadLocal k, Object v) {
6         super(k);
7         value = v;
8     }
9 }

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

 

ThreadLocalMap的成員變量:

 1 static class ThreadLocalMap {
 2     /**
 3      * The initial capacity -- MUST be a power of two.
 4      */
 5     private static final int INITIAL_CAPACITY = 16;
 6 
 7     /**
 8      * The table, resized as necessary.
 9      * table.length MUST always be a power of two.
10      */
11     private Entry[] table;
12 
13     /**
14      * The number of entries in the table.
15      */
16     private int size = 0;
17 
18     /**
19      * The next size value at which to resize.
20      */
21     private int threshold; // Default to 0
22 }

Hash沖突怎么解決

和HashMap的最大的不同在於,ThreadLocalMap結構非常簡單,沒有next引用,也就是說ThreadLocalMap中解決Hash沖突的方式並非鏈表的方式,

而是采用線性探測的方式,所謂線性探測,就是根據初始key的hashcode值確定元素在table數組中的位置,如果發現這個位置上已經有其他key值的元素被占用,

則利用固定的算法尋找一定步長的下個位置,依次判斷,直至找到能夠存放的位置。

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

 1 /**
 2  * Increment i modulo len.
 3  */
 4 private static int nextIndex(int i, int len) {
 5     return ((i + 1 < len) ? i + 1 : 0);
 6 }
 7 
 8 /**
 9  * Decrement i modulo len.
10  */
11 private static int prevIndex(int i, int len) {
12     return ((i - 1 >= 0) ? i - 1 : len - 1);
13 }

顯然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方法。

應用場景

還記得Hibernate的session獲取場景嗎

 1 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
 2 
 3 //獲取Session
 4 public static Session getCurrentSession(){
 5     Session session =  threadLocal.get();
 6     //判斷Session是否為空,如果為空,將創建一個session,並設置到本地線程變量中
 7     try {
 8         if(session ==null&&!session.isOpen()){
 9             if(sessionFactory==null){
10                 rbuildSessionFactory();// 創建Hibernate的SessionFactory
11             }else{
12                 session = sessionFactory.openSession();
13             }
14         }
15         threadLocal.set(session);
16     } catch (Exception e) {
17         // TODO: handle exception
18     }
19 
20     return session;
21 }

每個線程訪問數據庫都應當是一個獨立的Session會話,如果多個線程共享同一個Session會話,有可能其他線程關閉連接了,當前線程再執行提交時就會出現會話已關閉的異常,

導致系統異常。此方式能避免線程爭搶Session,提高並發下的安全性。

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



總結

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM