Java并发编程—ThreadLocal底层原理
作者:Java3y
鏈接:https://www.zhihu.com/question/341005993/answer/793627819
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
?
一、什么是ThreadLocal
聲明:本文使用的是JDK 1.8首先我們來看一下JDK的文檔介紹:
/*** This class provides thread-local variables. These variables differ from* their normal counterparts in that each thread that accesses one (via its* {@code get} or {@code set} method) has its own, independently initialized* copy of the variable. {@code ThreadLocal} instances are typically private* static fields in classes that wish to associate state with a thread (e.g.,* a user ID or Transaction ID).* * <p>For example, the class below generates unique identifiers local to each* thread.* A thread's id is assigned the first time it invokes {@code ThreadId.get()}* and remains unchanged on subsequent calls.*/結合我的總結可以這樣理解:ThreadLocal提供了線程的局部變量,每個線程都可以通過set()和get()來對這個局部變量進行操作,但不會和其他線程的局部變量進行沖突,實現了線程的數據隔離~。簡要言之:往ThreadLocal中填充的變量屬于當前線程,該變量對其他線程而言是隔離的。
二、為什么要學習ThreadLocal?
從上面可以得出:ThreadLocal可以讓我們擁有當前線程的變量,那這個作用有什么用呢???
2.1管理Connection
最典型的是管理數據庫的Connection:當時在學JDBC的時候,為了方便操作寫了一個簡單數據庫連接池,需要數據庫連接池的理由也很簡單,頻繁創建和關閉Connection是一件非常耗費資源的操作,因此需要創建數據庫連接池~那么,數據庫連接池的連接怎么管理呢??我們交由ThreadLocal來進行管理。為什么交給它來管理呢??ThreadLocal能夠實現當前線程的操作都是用同一個Connection,保證了事務!當時候寫的代碼:
public class DBUtil {//數據庫連接池private static BasicDataSource source;//為不同的線程管理連接private static ThreadLocal<Connection> local;static {try {//加載配置文件Properties properties = new Properties();//獲取讀取流InputStream stream = DBUtil.class.getClassLoader().getResourceAsStream("連接池/config.properties");//從配置文件中讀取數據properties.load(stream);//關閉流stream.close();//初始化連接池source = new BasicDataSource();//設置驅動source.setDriverClassName(properties.getProperty("driver"));//設置urlsource.setUrl(properties.getProperty("url"));//設置用戶名source.setUsername(properties.getProperty("user"));//設置密碼source.setPassword(properties.getProperty("pwd"));//設置初始連接數量source.setInitialSize(Integer.parseInt(properties.getProperty("initsize")));//設置最大的連接數量source.setMaxActive(Integer.parseInt(properties.getProperty("maxactive")));//設置最長的等待時間source.setMaxWait(Integer.parseInt(properties.getProperty("maxwait")));//設置最小空閑數source.setMinIdle(Integer.parseInt(properties.getProperty("minidle")));//初始化線程本地local = new ThreadLocal<>(); } catch (IOException e) {e.printStackTrace();}}public static Connection getConnection() throws SQLException {//獲取Connection對象Connection connection = source.getConnection();//把Connection放進ThreadLocal里面local.set(connection);//返回Connection對象return connection;}//關閉數據庫連接public static void closeConnection() {//從線程中拿到Connection對象Connection connection = local.get();try {if (connection != null) {//恢復連接為自動提交connection.setAutoCommit(true);//這里不是真的把連接關了,只是將該連接歸還給連接池connection.close();//既然連接已經歸還給連接池了,ThreadLocal保存的Connction對象也已經沒用了local.remove();}} catch (SQLException e) {e.printStackTrace();}} }同樣的,Hibernate對Connection的管理也是采用了相同的手法(使用ThreadLocal,當然了Hibernate的實現是更強大的)~
三、ThreadLocal實現的原理
想要更好地去理解ThreadLocal,那就得翻翻它是怎么實現的了~~~
聲明:本文使用的是JDK 1.8首先,我們來看一下ThreadLocal的set()方法,因為我們一般使用都是new完對象,就往里邊set對象了
public void set(T value) {// 得到當前線程對象Thread t = Thread.currentThread();// 這里獲取ThreadLocalMapThreadLocalMap map = getMap(t);// 如果map存在,則將當前線程對象t作為key,要存儲的對象作為value存到map里面去if (map != null)map.set(this, value);elsecreateMap(t, value);}上面有個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是ThreadLocal的一個內部類。用Entry類來進行存儲。我們的值都是存儲到這個Map上的,key是當前ThreadLocal對象!如果該Map不存在,則初始化一個:
void createMap(Thread t, T firstValue) {t.threadLocals = new ThreadLocalMap(this, firstValue);}如果該Map存在,則從Thread中獲取!
/*** Get the map associated with a ThreadLocal. Overridden in* InheritableThreadLocal.** @param t the current thread* @return the map*/ThreadLocalMap getMap(Thread t) {return t.threadLocals;}Thread維護了ThreadLocalMap變量
/* ThreadLocal values pertaining to this thread. This map is maintained* by the ThreadLocal class. */ThreadLocal.ThreadLocalMap threadLocals = null從上面又可以看出,ThreadLocalMap是在ThreadLocal中使用內部類來編寫的,但對象的引用是在Thread中!于是我們可以總結出:Thread為每個線程維護了ThreadLocalMap這么一個Map,而ThreadLocalMap的key是LocalThread對象本身,value則是要存儲的對象。有了上面的基礎,我們看get()方法就一點都不難理解了:
public T get() {Thread t = Thread.currentThread();ThreadLocalMap map = getMap(t);if (map != null) {ThreadLocalMap.Entry e = map.getEntry(this);if (e != null) {@SuppressWarnings("unchecked")T result = (T)e.value;return result;}}return setInitialValue();}3.1ThreadLocal原理總結
正因為這個原理,所以ThreadLocal能夠實現“數據隔離”,獲取當前線程的局部變量值,不受其他線程影響~
四、避免內存泄露
我們來看一下ThreadLocal的對象關系引用圖:
ThreadLocal內存泄漏的根源是:由于ThreadLocalMap的生命周期跟Thread一樣長,如果沒有手動刪除對應key就會導致內存泄漏,而不是因為弱引用。
想要避免內存泄露就要手動remove()掉!
五、總結
ThreadLocal這方面的博文真的是數不勝數,隨便一搜就很多很多~站在前人的肩膀上總結了這篇博文~
最后要記住的是:ThreadLocal設計的目的就是為了能夠在當前線程中有屬于自己的變量,并不是為了解決并發或者共享變量的問題
有幫助?點贊!
關注我的公眾號:Java3y,獲取更多的原創筆記,海量視頻資源/原創思維導圖/學習路線
所有的文章導航:https://github.com/ZhongFuCheng3y/3y(歡迎star)
總結
以上是生活随笔為你收集整理的Java并发编程—ThreadLocal底层原理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java并发编程—ThreadLocal
- 下一篇: java.lang包—类Class应用之