ThreadLocal是線程私有的局部變量存儲容器,能夠理解成每一個線程都有本身專屬的存儲容器,用來存儲線程私有變量。ThreadLocal 在平常開發框架中應用普遍,但用很差也會出現各類問題,本文就此講解一下。java
ThreadLocal 的常見應用場景有兩種:spring
多線程訪問同一個共享變量的時候容易出現併發問題,特別是多個線程對一個變量進行寫入的時候,爲了保證線程安全,通常使用者在訪問共享變量的時候須要進行額外的同步措施才能保證線程安全性,如:synchronized、Lock之類的鎖。數據庫
ThreadLocal是除了加鎖這種同步方式以外的一種,規避多線程訪問出現線程不安全的方法。當咱們在建立一個變量後,若是每一個線程對其進行訪問的時候訪問的都是線程本身的變量,這樣就不會存在線程不安全問題。數組
ThreadLocal是JDK包提供的,它提供線程本地變量,若是建立一個ThreadLocal變量,那麼訪問這個變量的每一個線程都會有這個變量的一個副本,在實際多線程操做的時候,操做的是本身本地內存中的變量,從而規避了線程安全問題。安全
這裏舉幾個例子:session
示例1:獲取接口的當前請求用戶
在後臺接口業務邏輯的全過程當中,若是須要在多個地方獲取當前請求用戶的信息。一般的一種作法就是:在接口請求時,經過過濾器、攔截器、AOP等方式,從session或token中獲取當前用戶信息,存入ThreadLocal中。多線程
在整個接口處理過程當中,若是沒有另外建立線程,均可以直接從ThreadLocal變量中獲取當前用戶,而無需再從Session、token中驗證和獲取用戶。這種方案設計不只提升性能,最重要的是將本來複雜的邏輯和代碼實現,變得簡潔明瞭。例以下面的這個例子:併發
(1)定義ThreadLocal變量:UserProfileThread.java框架
public class UserProfileThread { private static ThreadLocal<UserProfile> USER_PROFILE_TL =new ThreadLocal<>(); public static void setUserProfile(UserProfile userProfile){ USER_PROFILE_TL.set(userProfile); } public static UserProfile getUserProfile() { return USER_PROFILE_TL.get(); } public static String getCurrentUser() { return Optional.ofNullable(USER_PROFILE_TL.get()) .map(UserProfile::getUid) .orElse(UserProfile.ANONYMOUS_USER); } }
(2)在過濾器中設置變量值:分佈式
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { UserProfile userProfile = null; // ... 驗證和獲取用戶信息 userProfile UserProfileThread.setUserProfile(userProfile); filterChain.doFilter(servletRequest, servletResponse); }
(3)獲取當前用戶信息
//獲取當前用戶 String uid=UserProfileThread.getCurrentUser(); //獲取當前用戶對象 UserProfile user=UserProfileThread.getUserProfile();
示例2:spring框架中保證數據庫事務在同一個鏈接下執行
要想實現jdbc事務, 就必須是在同一個鏈接對象中操做,多個鏈接下事務就會不可控,須要藉助分佈式事務完成。那spring框架如何保證數據庫事務在同一個鏈接下執行的呢?
DataSourceTransactionManager 是spring的數據源事務管理器,它會在你調用getConnection()的時候從數據庫鏈接池中獲取一個connection, 而後將其與ThreadLocal綁定,事務完成後解除綁定。這樣就保證了事務在同一鏈接下完成。
ThreadLocal類提供set/get方法存儲和獲取value值,但實際上ThreadLocal類並不存儲value值,真正存儲是靠ThreadLocalMap這個類。
每一個線程實例都對應一個TheadLocalMap實例,咱們能夠在同一個線程裏實例化不少個ThreadLocal來存儲不少種類型的值,這些ThreadLocal實例分別做爲key,對應各自的value,最終存儲在Entry table數組中。
咱們看看ThreadLocal的set方法:
public class ThreadLocal<T> { 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的邏輯比較簡單,就是獲取當前線程的ThreadLocalMap,而後往map裏添加KV,K是當前ThreadLocal實例,V是咱們傳入的value。這裏須要注意一下,map的獲取是須要從Thread類對象裏面取,看一下Thread類的定義。
public class Thread implements Runnable { ThreadLocal.ThreadLocalMap threadLocals = null; //省略其餘 }
Thread類維護了一個ThreadLocalMap的變量引用。
所以,咱們能夠得出以下結論:
ThreadLocal實例有提供remove()方法,用於回收對象,清除對應的內存佔用。這個方法一般容易被忽略,而致使出現了各類問題。以下面幾種: