threadlocal是在多線程環境下經常使用的一個類。
這個類并不是為了解決多線程間共享變量的問題。舉個例子,在一個電商系統中,用一個long型變量表示某個商品的庫存量,多個線程需要訪問庫存量進行銷售,并減去銷售數量,以更新庫存量。在這個場景中,是不能使用threadlocal類的。
threadlocal適用的場景是,多個線程都需要使用一個變量,但這個變量的值不需要在各個線程間共享,各個線程都只使用自己的這個變量的值。這樣的場景下,可以使用threadlocal。此外,我們使用threadlocal還能解決一個參數過多的問題。例如一個線程內的某個方法f1有10個參數,而f1調用f2時,f2又有10個參數,這么多的參數傳遞十分繁瑣。那么,我們可以使用threadlocal來減少參數的傳遞,用threadlocal定義全局變量,各個線程需要參數時,去全局變量去取就可以了。
接下來我們看一下threadlocal的源碼。首先是類的介紹。如下圖。這個類提供了線程本地變量。這些變量使每個線程都有自己的一份拷貝。threadlocal期望能夠管理一個線程的狀態,例如用戶id或事務id。例如下面的例子產生線程本地的唯一id。線程的id是第一次調用時進行復制,并且在后面的調用中保持不變。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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方法的作用是,把線程本地變量的當前線程的拷貝設置為指定的值。大部分子類無需重寫該方法。首先獲取當前線程,然后獲取當前線程的threadlocalmap。如果threadlocalmap不為null,則設置當前線程的值為指定的值,否則調用createmap方法。
獲取線程的threadlocalmap對象,是直接返回的線程的threadlocals,類型為threadlocalmap。也就是說,每個線程都有一個threadlocalmap對象,用于保存該線程關聯的所有的threadlocal類型的變量。threadlocalmap的key是threadlocal,value是該threadlocal對應的值。具體什么意思呢?在程序中,我們可以定義不止一個threadlocal對象,一般會有多個,比如定義3個threadlocal<string>,再定義2個threadlocal<integer>,而每個線程可能都需要訪問全部這些threadlocal的變量,那么,我們用什么數據結構來實現呢?當然,最好的方式就是像源碼中的這樣,每個線程有一個threadlocalmap,key為threadlocal變量名,而value為該線程在該threadlocal變量的值。這個設計實在是太巧妙了。
寫到這里,自己回想起之前換工作面試時,面試官問自己關于threadlocal的實現原理。那個時候,為了準備面試,自己只在網上看了一些面試題,并沒有真正掌握,在回答這個問題時,我有印象,自己回答的是用一個map,線程的id值作為key,變量值作為value,誒,露餡了啊。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
/** * 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變量對應的value,然后返回value。如果threadlocalmap為null,則說明該線程還沒有設置該threadlocal變量的值,那么就返回setinitialvalue方法的返回值。其中的initialvalue方法的返回值,通常情況下為null。但是,子類可以重寫initialvalue方法以返回期望的值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
/** * 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的靜態內部類。它對hashmap進行了改造,用于保存各個threadlocal變量和某線程的該變量的值的映射關系。每個線程都有一個threadlocalmap類型的屬性。threadlocalmap中的table數組的長度,與該線程訪問的threadlocal類型變量的個數有關,而與別的無關。
this is the end。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:https://blog.csdn.net/li_canhui/article/details/85231116