Java源碼解析ThreadLocal及使用場景
ThreadLocal是在多線程環(huán)境下經(jīng)常使用的一個類。
這個類并不是為了解決多線程間共享變量的問題。舉個例子,在一個電商系統(tǒng)中,用一個Long型變量表示某個商品的庫存量,多個線程需要訪問庫存量進行銷售,并減去銷售數(shù)量,以更新庫存量。在這個場景中,是不能使用ThreadLocal類的。
ThreadLocal適用的場景是,多個線程都需要使用一個變量,但這個變量的值不需要在各個線程間共享,各個線程都只使用自己的這個變量的值。這樣的場景下,可以使用ThreadLocal。此外,我們使用ThreadLocal還能解決一個參數(shù)過多的問題。例如一個線程內(nèi)的某個方法f1有10個參數(shù),而f1調(diào)用f2時,f2又有10個參數(shù),這么多的參數(shù)傳遞十分繁瑣。那么,我們可以使用ThreadLocal來減少參數(shù)的傳遞,用ThreadLocal定義全局變量,各個線程需要參數(shù)時,去全局變量去取就可以了。
接下來我們看一下ThreadLocal的源碼。首先是類的介紹。如下圖。這個類提供了線程本地變量。這些變量使每個線程都有自己的一份拷貝。ThreadLocal期望能夠管理一個線程的狀態(tài),例如用戶id或事務(wù)id。例如下面的例子產(chǎn)生線程本地的唯一id。線程的id是第一次調(diào)用時進行復(fù)制,并且在后面的調(diào)用中保持不變。
This class provides thread-local variables.
These variables differ from their normal counterparts in that each thread that accesses
one (via its get or set method) has its own, independently initialized copy of the variable. 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).
For example, the class below generates unique identifiers local to each thread.
A thread's id is assigned the first time it invokes ThreadId.get() and
remains unchanged on subsequent calls.
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
Each thread holds an implicit reference to its copy of a thread-local
variable as long as the thread is alive and the ThreadLocal instance is
accessible; after a thread goes away, all of its copies of thread-local
instances are subject to garbage collection (unless other references to
these copies exist).
下面看一下set方法。
set方法的作用是,把線程本地變量的當前線程的拷貝設(shè)置為指定的值。大部分子類無需重寫該方法。首先獲取當前線程,然后獲取當前線程的ThreadLocalMap。如果ThreadLocalMap不為null,則設(shè)置當前線程的值為指定的值,否則調(diào)用createMap方法。
獲取線程的ThreadLocalMap對象,是直接返回的線程的threadLocals,類型為ThreadLocalMap。也就是說,每個線程都有一個ThreadLocalMap對象,用于保存該線程關(guān)聯(lián)的所有的ThreadLocal類型的變量。ThreadLocalMap的key是ThreadLocal,value是該ThreadLocal對應(yīng)的值。具體什么意思呢?在程序中,我們可以定義不止一個ThreadLocal對象,一般會有多個,比如定義3個ThreadLocal<String>,再定義2個ThreadLocal<Integer>,而每個線程可能都需要訪問全部這些ThreadLocal的變量,那么,我們用什么數(shù)據(jù)結(jié)構(gòu)來實現(xiàn)呢?當然,最好的方式就是像源碼中的這樣,每個線程有一個ThreadLocalMap,key為ThreadLocal變量名,而value為該線程在該ThreadLocal變量的值。這個設(shè)計實在是太巧妙了。
寫到這里,自己回想起之前換工作面試時,面試官問自己關(guān)于ThreadLocal的實現(xiàn)原理。那個時候,為了準備面試,自己只在網(wǎng)上看了一些面試題,并沒有真正掌握,在回答這個問題時,我有印象,自己回答的是用一個map,線程的id值作為key,變量值作為value,誒,露餡了啊。
/**
* 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);
}
/**
* 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;
}
/**
* 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);
}
接下來看一下get方法。
源碼如下。首先獲取當前線程的ThreadLocalMap,然后,從ThreadLocalMap獲取該ThreadLocal變量對應(yīng)的value,然后返回value。如果ThreadLocalMap為null,則說明該線程還沒有設(shè)置該ThreadLocal變量的值,那么就返回setInitialValue方法的返回值。其中的initialValue方法的返回值,通常情況下為null。但是,子類可以重寫initialValue方法以返回期望的值。
/**
* 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) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
/**
* Variant of set() to establish initialValue. Used instead
* of set() in case user has overridden the set() method.
* @return the initial value
**/
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;
}
文章的最后,簡單介紹一下ThreadLocalMap這個類,該類是ThreadLocal的靜態(tài)內(nèi)部類。它對HashMap進行了改造,用于保存各個ThreadLocal變量和某線程的該變量的值的映射關(guān)系。每個線程都有一個ThreadLocalMap類型的屬性。ThreadLocalMap中的table數(shù)組的長度,與該線程訪問的ThreadLocal類型變量的個數(shù)有關(guān),而與別的無關(guān)。
This is the end。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
在idea2023中使用SpringBoot整合Lombok全過程及詳細用法
Lombok項目是一個java庫,它可以自動插入到編輯器和構(gòu)建工具中,增強java的性能,本文詳細給大家介紹了在idea2023中使用SpringBoot整合Lombok全過程及詳細用法,需要的朋友可以參考下2023-09-09
詳解Springboot應(yīng)用啟動以及關(guān)閉時完成某些操作
這篇文章主要介紹了詳解Springboot應(yīng)用啟動以及關(guān)閉時完成某些操作,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
java?Stream流常見操作方法(反射,類加載器,類加載,反射)
這篇文章主要介紹了java?Stream流常見操作方法(反射,類加載器,類加載,反射),文章圍繞主題展開詳細的內(nèi)容介紹,展開詳細的內(nèi)容介紹,具有一定參考價值,感興趣的小伙伴可以參考一下2022-06-06

