threadlocal翻譯成中文比較準確的叫法應該是:線程局部變量。
threadlocal是什么
早在jdk 1.2的版本中就提供java.lang.threadlocal,threadlocal為解決多線程程序的并發問題提供了一種新的思路。使用這個工具類可以很簡潔地編寫出優美的多線程程序。
當使用threadlocal維護變量時,threadlocal為每個使用該變量的線程提供獨立的變量副本,所以每一個線程都可以獨立地改變自己的副本,而不會影響其它線程所對應的副本。
從線程的角度看,目標變量就象是線程的本地變量,這也是類名中“local”所要表達的意思。
所以,在java中編寫線程局部變量的代碼相對來說要笨拙一些,因此造成線程局部變量沒有在java開發者中得到很好的普及。
threadlocal的接口方法
- threadlocal類接口很簡單,只有4個方法,我們先來了解一下:
- void set(object value)設置當前線程的線程局部變量的值。
- public object get()該方法返回當前線程所對應的線程局部變量。
- public void remove()將當前線程局部變量的值刪除,目的是為了減少內存的占用,該方法是jdk 5.0新增的方法。需要指出的是,當線程結束后,對應該線程的局部變量將自動被垃圾回收,所以顯式調用該方法清除線程的局部變量并不是必須的操作,但它可以加快內存回收的速度。
- protected object initialvalue()返回該線程局部變量的初始值,該方法是一個protected的方法,顯然是為了讓子類覆蓋而設計的。這個方法是一個延遲調用方法,在線程第1次調用get()或set(object)時才執行,并且僅執行1次。threadlocal中的缺省實現直接返回一個null。
值得一提的是,在jdk5.0中,threadlocal已經支持泛型,該類的類名已經變為threadlocal<t>。api方法也相應進行了調整,新版本的api方法分別是void set(t value)、t get()以及t initialvalue()。
threadlocal是如何做到為每一個線程維護變量的副本的呢?其實實現的思路很簡單:在threadlocal類中有一個map,用于存儲每一個線程的變量副本,map中元素的鍵為線程對象,而值對應線程的變量副本。我們自己就可以提供一個簡單的實現版本:
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
|
package com.test; public class testnum { // ①通過匿名內部類覆蓋threadlocal的initialvalue()方法,指定初始值 private static threadlocal<integer> seqnum = new threadlocal<integer>() { public integer initialvalue() { return 0 ; } }; // ②獲取下一個序列值 public int getnextnum() { seqnum.set(seqnum.get() + 1 ); return seqnum.get(); } public static void main(string[] args) { testnum sn = new testnum(); // ③ 3個線程共享sn,各自產生序列號 testclient t1 = new testclient(sn); testclient t2 = new testclient(sn); testclient t3 = new testclient(sn); t1.start(); t2.start(); t3.start(); } private static class testclient extends thread { private testnum sn; public testclient(testnum sn) { this .sn = sn; } public void run() { for ( int i = 0 ; i < 3 ; i++) { // ④每個線程打出3個序列值 system.out.println( "thread[" + thread.currentthread().getname() + "] --> sn[" + sn.getnextnum() + "]" ); } } } } |
通常我們通過匿名內部類的方式定義threadlocal的子類,提供初始的變量值,如例子中①處所示。testclient線程產生一組序列號,在③處,我們生成3個testclient,它們共享同一個testnum實例。運行以上代碼,在控制臺上輸出以下的結果:
thread[thread-0] --> sn[1]
thread[thread-1] --> sn[1]
thread[thread-2] --> sn[1]
thread[thread-1] --> sn[2]
thread[thread-0] --> sn[2]
thread[thread-1] --> sn[3]
thread[thread-2] --> sn[2]
thread[thread-0] --> sn[3]
thread[thread-2] --> sn[3]
考察輸出的結果信息,我們發現每個線程所產生的序號雖然都共享同一個testnum實例,但它們并沒有發生相互干擾的情況,而是各自產生獨立的序列號,這是因為我們通過threadlocal為每一個線程提供了單獨的副本。
thread同步機制的比較
threadlocal和線程同步機制相比有什么優勢呢?threadlocal和線程同步機制都是為了解決多線程中相同變量的訪問沖突問題。
在同步機制中,通過對象的鎖機制保證同一時間只有一個線程訪問變量。這時該變量是多個線程共享的,使用同步機制要求程序慎密地分析什么時候對變量進行讀寫,什么時候需要鎖定某個對象,什么時候釋放對象鎖等繁雜的問題,程序設計和編寫難度相對較大。
而threadlocal則從另一個角度來解決多線程的并發訪問。threadlocal會為每一個線程提供一個獨立的變量副本,從而隔離了多個線程對數據的訪問沖突。因為每一個線程都擁有自己的變量副本,從而也就沒有必要對該變量進行同步了。threadlocal提供了線程安全的共享對象,在編寫多線程代碼時,可以把不安全的變量封裝進threadlocal。
由于threadlocal中可以持有任何類型的對象,低版本jdk所提供的get()返回的是object對象,需要強制類型轉換。但jdk 5.0通過泛型很好的解決了這個問題,在一定程度地簡化threadlocal的使用,代碼清單 9 2就使用了jdk 5.0新的threadlocal<t>版本。
概括起來說,對于多線程資源共享的問題,同步機制采用了“以時間換空間”的方式,而threadlocal采用了“以空間換時間”的方式。前者僅提供一份變量,讓不同的線程排隊訪問,而后者為每一個線程都提供了一份變量,因此可以同時訪問而互不影響。
spring使用threadlocal解決線程安全問題我們知道在一般情況下,只有無狀態的bean才可以在多線程環境下共享,在spring中,絕大部分bean都可以聲明為singleton作用域。就是因為spring對一些bean(如requestcontextholder、transactionsynchronizationmanager、localecontextholder等)中非線程安全狀態采用threadlocal進行處理,讓它們也成為線程安全的狀態,因為有狀態的bean就可以在多線程中共享了。
一般的web應用劃分為展現層、服務層和持久層三個層次,在不同的層中編寫對應的邏輯,下層通過接口向上層開放功能調用。在一般情況下,從接收請求到返回響應所經過的所有程序調用都同屬于一個線程,如圖9?2所示:
通通透透理解threadlocal
同一線程貫通三層這樣你就可以根據需要,將一些非線程安全的變量以threadlocal存放,在同一次請求響應的調用線程中,所有關聯的對象引用到的都是同一個變量。
下面的實例能夠體現spring對有狀態bean的改造思路:
代碼清單3 testdao:非線程安全
1
2
3
4
5
6
7
8
9
10
11
|
package com.test; import java.sql.connection; import java.sql.sqlexception; import java.sql.statement; public class testdao { private connection conn; // ①一個非線程安全的變量 public void addtopic() throws sqlexception { statement stat = conn.createstatement(); // ②引用非線程安全變量 // … } } |
由于①處的conn是成員變量,因為addtopic()方法是非線程安全的,必須在使用時創建一個新topicdao實例(非singleton)。下面使用threadlocal對conn這個非線程安全的“狀態”進行改造:
代碼清單4 testdao:線程安全
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.test; import java.sql.connection; import java.sql.sqlexception; import java.sql.statement; public class testdaonew { // ①使用threadlocal保存connection變量 private static threadlocal<connection> connthreadlocal = new threadlocal<connection>(); public static connection getconnection() { // ②如果connthreadlocal沒有本線程對應的connection創建一個新的connection, // 并將其保存到線程本地變量中。 if (connthreadlocal.get() == null ) { connection conn = getconnection(); connthreadlocal.set(conn); return conn; } else { return connthreadlocal.get(); // ③直接返回線程本地變量 } } public void addtopic() throws sqlexception { // ④從threadlocal中獲取線程對應的connection statement stat = getconnection().createstatement(); } } |
不同的線程在使用topicdao時,先判斷connthreadlocal.get()是否是null,如果是null,則說明當前線程還沒有對應的connection對象,這時創建一個connection對象并添加到本地線程變量中;如果不為null,則說明當前的線程已經擁有了connection對象,直接使用就可以了。這樣,就保證了不同的線程使用線程相關的connection,而不會使用其它線程的connection。因此,這個topicdao就可以做到singleton共享了。
當然,這個例子本身很粗糙,將connection的threadlocal直接放在dao只能做到本dao的多個方法共享connection時不發生線程安全問題,但無法和其它dao共用同一個connection,要做到同一事務多dao共享同一connection,必須在一個共同的外部類使用threadlocal保存connection。
connectionmanager.java
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
|
package com.test; import java.sql.connection; import java.sql.drivermanager; import java.sql.sqlexception; public class connectionmanager { private static threadlocal<connection> connectionholder = new threadlocal<connection>() { @override protected connection initialvalue() { connection conn = null ; try { conn = drivermanager.getconnection( "jdbc:mysql://localhost:3306/test" , "username" , "password" ); } catch (sqlexception e) { e.printstacktrace(); } return conn; } }; public static connection getconnection() { return connectionholder.get(); } public static void setconnection(connection conn) { connectionholder.set(conn); } } |
java.lang.threadlocal<t>的具體實現
那么到底threadlocal類是如何實現這種“為每個線程提供不同的變量拷貝”的呢?先來看一下threadlocal的set()方法的源碼是如何實現的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/** * 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); } |
在這個方法內部我們看到,首先通過getmap(thread t)方法獲取一個和當前線程相關的threadlocalmap,然后將變量的值設置到這個threadlocalmap對象中,當然如果獲取到的threadlocalmap對象為空,就通過createmap方法創建。
線程隔離的秘密,就在于threadlocalmap這個類。threadlocalmap是threadlocal類的一個靜態內部類,它實現了鍵值對的設置和獲?。▽Ρ萴ap對象來理解),每個線程中都有一個獨立的threadlocalmap副本,它所存儲的值,只能被當前線程讀取和修改。threadlocal類通過操作每一個線程特有的threadlocalmap副本,從而實現了變量訪問在不同線程中的隔離。因為每個線程的變量都是自己特有的,完全不會有并發錯誤。還有一點就是,threadlocalmap存儲的鍵值對中的鍵是this對象指向的threadlocal對象,而值就是你所設置的對象了。
為了加深理解,我們接著看上面代碼中出現的getmap和createmap方法的實現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/** * 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 * @param map the map to store. */ void createmap(thread t, t firstvalue) { t.threadlocals = new threadlocalmap( this , firstvalue); } |
接下來再看一下threadlocal類中的get()方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/** * 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 ) return (t)e.value; } return setinitialvalue(); } |
再來看setinitialvalue()方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/** * 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; } |
獲取和當前線程綁定的值時,threadlocalmap對象是以this指向的threadlocal對象為鍵進行查找的,這當然和前面set()方法的代碼是相呼應的。
進一步地,我們可以創建不同的threadlocal實例來實現多個變量在不同線程間的訪問隔離,為什么可以這么做?因為不同的threadlocal對象作為不同鍵,當然也可以在線程的threadlocalmap對象中設置不同的值了。通過threadlocal對象,在多線程中共享一個值和多個值的區別,就像你在一個hashmap對象中存儲一個鍵值對和多個鍵值對一樣,僅此而已。
小結
threadlocal是解決線程安全問題一個很好的思路,它通過為每個線程提供一個獨立的變量副本解決了變量并發訪問的沖突問題。在很多情況下,threadlocal比直接使用synchronized同步機制解決線程安全問題更簡單,更方便,且結果程序擁有更高的并發性。
connectionmanager.java
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
|
package com.test; import java.sql.connection; import java.sql.drivermanager; import java.sql.sqlexception; public class connectionmanager { private static threadlocal<connection> connectionholder = new threadlocal<connection>() { @override protected connection initialvalue() { connection conn = null ; try { conn = drivermanager.getconnection( "jdbc:mysql://localhost:3306/test" , "username" , "password" ); } catch (sqlexception e) { e.printstacktrace(); } return conn; } }; public static connection getconnection() { return connectionholder.get(); } public static void setconnection(connection conn) { connectionholder.set(conn); } } |
后記
看到網友評論的很激烈,甚至關于threadlocalmap不是threadlocal里面的,而是thread里面的這種評論都出現了,于是有了這個后記,下面先把jdk源碼貼上,源碼最有說服力了。
1
2
3
4
5
6
7
8
9
10
|
/** * threadlocalmap is a customized hash map suitable only for * maintaining thread local values. no operations are exported * outside of the threadlocal class. the class is package private to * allow declaration of fields in class thread. to help deal with * very large and long-lived usages, the hash table entries use * weakreferences for keys. however, since reference queues are not * used, stale entries are guaranteed to be removed only when * the table starts running out of space. */ static class threadlocalmap {...} |
源碼就是以上,這源碼自然是在threadlocal里面的,有截圖為證。
本文是自己在學習threadlocal的時候,一時興起,深入看了源碼,思考了此類的作用、使用范圍,進而聯想到對傳統的synchronize共享變量線程安全的問題進行比較,而總結的博文,總結一句話就是一個是鎖機制進行時間換空間,一個是存儲拷貝進行空間換時間。
以上所述是小編給大家介紹的徹底理解java中的threadlocal,希望對大家有所幫助
原文鏈接:http://blog.csdn.net/lufeng20/article/details/24314381