1 什么是ThreadLocal
ThreadLocal,翻譯過來,就是"線程本地變量",它是從JDK1.2開始提供的一個(gè)類,它能夠?yàn)椴煌木€程提供單獨(dú)的變量副本,使得當(dāng)在不同的線程調(diào)用變量的時(shí)候互不干擾。
從名字可以得到兩個(gè)關(guān)鍵信息,
線程——該對象是被線程所持有的;
本地變量——這個(gè)變量作用域在線程內(nèi);
2 ThreadLocal給夠給我們帶來什么
- 解決多線程下的資源競爭問題;
- 全局共享變量;
2.1 解決多線程下的資源競爭問題
假如有一個(gè)動(dòng)物園,猴子那個(gè)扎堆啊 = = , 管理員那個(gè)扎心啊 T_T。開始的時(shí)候,整個(gè)猴子園就一只碗,每次猴子要吃香蕉的時(shí)候就在碗里放一只香蕉。碗就相當(dāng)于向園長(操作系統(tǒng))申請的空間,就只有一個(gè)啦,每只猴子(線程)應(yīng)該都有自己的一根香蕉(變量)。
如果照正常情況下,管理員要避免猴子們爭奪食物,會(huì)讓猴子們排隊(duì),一只猴子一只猴子的喂,每次往碗里放一根香蕉。排一長隊(duì),猴子當(dāng)然痛恨要抗議啊,因?yàn)橛行┖镒映缘寐?,后面的猴子猴孫就等不住了。管理員也要耗費(fèi)相當(dāng)?shù)臅r(shí)間,管理員也郁悶。
于是,管理員干脆向園長申請了又一批碗,干脆一個(gè)猴子一只碗算了。這時(shí)候,一只猴子一只碗,互不干擾,喂猴子的時(shí)間節(jié)約了不少。
ThreadLocal就是這么一個(gè)情況,為每一個(gè)線程都創(chuàng)建一個(gè)線程本地的變量來存儲(chǔ)數(shù)據(jù),當(dāng)線程需要使用的時(shí)候直接取出來用就可以了。而不必?fù)?dān)心變量被其他的線程所篡改。
2.2 共享變量
這個(gè)也很好理解。給每個(gè)猴子分配一只碗以后,猴子要怎么使用這個(gè)碗,完全由他自己決定,有碗,真的可以玩所欲為的,他想什么時(shí)候用他就什么時(shí)候用,碗里的香蕉他想什么時(shí)候吃他就什么時(shí)候吃。
與之類似,線程中一旦存了具體的數(shù)據(jù),只要在線程內(nèi)部,什么時(shí)候取出來都可以。有時(shí)候參數(shù)傳遞不是最佳的解決方案,那么就設(shè)置一個(gè)全局變量吧,比如在View層設(shè)置一個(gè)變量,然后在Service層再取出來用。是不是有點(diǎn)像緩存呢?
2.3 如何使用
如這個(gè)例子所示:
private static void testThreaLoacl(){
final ThreadLocal<String> tl = new ThreadLocal<String>();
String threadName = Thread.currentThread().getName();
tl.set(threadName);
new Thread(){
@Override
public void run() {
System.out.println("---------start");
String name = tl.get();
System.out.println(name);
System.out.println("---------end");
}
}.start();
String name = tl.get();
System.out.println(name);
}
運(yùn)行結(jié)果:
---------start
null
---------start
main
- 先new出一個(gè)ThreadLocal對象,然后直接set進(jìn)去value,然后在想要使用的地方使用就可以了;
- 因?yàn)樽兞渴蔷€程內(nèi)部獨(dú)享的。當(dāng)在main線程set的時(shí)候,在子線程中是無法獲取到main線程set的值的。
3 經(jīng)典使用場景
很多框架匯總都可以看到ThreadLocal的影子。
? 1.Spring中的事務(wù)控制。大致的流程是
向數(shù)據(jù)庫獲取一個(gè)Connnection,然后存到ThreadLocal中去,然后調(diào)用業(yè)務(wù)方法,最后再從ThreadLocal中取出Connnection,commit!
? 2.playFrameWork1.0中的請求參數(shù)。
可能很多寶寶都不知道PlayFrameWork!,它是一個(gè)java的全棧式框架啦,然后略略略(講不完)….在它的1.0版本中,請求參數(shù)在整個(gè)MVC三層都可以輕松取得,如,Params.params,原因只是因?yàn)樗鼜囊婚_始就將請求參數(shù)存到ThreadLocal里面去了。
4 使用ThreadLocal需要注意什么
-
ThreadLocal并不能保證數(shù)據(jù)是安全的。而且,看一下源碼就可以發(fā)現(xiàn)。
/** * 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 { static class Entry extends WeakReference<ThreadLocal> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal k, Object v) { super(k); value = v; } }ThreadLocal內(nèi)部使用到了一個(gè)ThreadLocalMap,具體的數(shù)據(jù)就是存在里面的Entry,而這個(gè)Entry是被定義為WeakReference弱引用的,注釋也說明了:為了避免變量的生命周期太長,所以采用弱引用,來確保在特定情況下能夠釋放這部分的空間。
-
容易造成代碼耦合。切勿濫用。畢竟每個(gè)線程都要為之分配空間,如果把ThreadLocal當(dāng)緩存使用,遲早要內(nèi)存溢出的。而且,共享變量的使用是先set,然后再get,如果你的某個(gè)方法中在get到這個(gè)共享變量,不然就會(huì)報(bào)錯(cuò),那你可能無法確保此時(shí)這個(gè)變量已經(jīng)被set了,甚至于,前面有人已經(jīng)set了共享變量,但是你并不知道,為了保險(xiǎn),你又作為一個(gè)參數(shù)傳了進(jìn)來。
例1:
static final ThreadLocal<String> tl = new ThreadLocal<String>(); public void method1() { tl.set("哦呼~"); method2(); } public void method2(){ System.out.println(tl.get().toString()); }可以看到,method1中已經(jīng)set了變量,然后method2直接從ThreadLocal中獲取并使用,如果method1中沒有set呢?method2就一定會(huì)出現(xiàn)空指針異常。method1根本就不知道調(diào)用method2要先set!這種情況下method1和method2之間的耦合度太高了!
怎么改?就按照正常的寫法就好啦。
例2:
public void method11(String value) { method22(value); } public void method22(String value){ System.out.println(value.toString()); }通過參數(shù)傳遞的參數(shù)傳遞進(jìn)來就好啦。此時(shí),method11很輕易就知道他需要傳參數(shù),那么就會(huì)將要打印的參數(shù)傳進(jìn)來(這里不考慮傳Null)。
-
使用ThreadLocal后,當(dāng)線程復(fù)用時(shí)可能會(huì)帶來一些副作用
看如下代碼:
public static void testThreadLocal2() {
final ThreadLocal<String> tl = new ThreadLocal<String>();
ExecutorService service = Executors.newFixedThreadPool(1);
service.submit(new Runnable() {
public void run() {
tl.set("hello");
}
});
service.submit(new Runnable() {
public void run() {
String name = tl.get();
System.out.println(name);
}
});
service.shutdown();
}
運(yùn)行結(jié)果:
hello
當(dāng)在一個(gè)線程池內(nèi)部,只有的幾個(gè)線程的時(shí)候,有很大概率會(huì)出現(xiàn)線程復(fù)用的情況。此時(shí),同一個(gè)線程的ThrealLocal是會(huì)被窺視到。
上述代碼中,我們以為第一個(gè)Runnable任務(wù)set的"hello",居然被第二個(gè)Runnable任務(wù)給get出來了。這不一定是我們預(yù)期的。
就比如,spring中,為了防止請求過多,我們可能會(huì)限制線程池的數(shù)量。當(dāng)A用戶的請求進(jìn)來了,使用了a線程,此時(shí)a中的ThreadLocal已經(jīng)被set了value,此時(shí)第B用戶的請求進(jìn)來了,假如a線程被復(fù)用了,那么B用戶中可以直接讀到a線程中A用戶set下的value。這里的數(shù)據(jù)就沒有被有效隔離開來。是絕對危險(xiǎn)的!
所以,使用了ThreadLocal之后,務(wù)必要記得清理ThreadLocal...
5 源碼概覽
-
ThreadLocal的基本組成
public class ThreadLocal<T> { private final int threadLocalHashCode = nextHashCode(); private static AtomicInteger nextHashCode = new AtomicInteger(); ... public T get() {...} public void set(T value) {...} public void remove() {...} ... static class ThreadLocalMap { ... Entry(ThreadLocal k, Object v) { super(k); value = v; } ... static class Entry extends WeakReference<ThreadLocal> {...} private Entry[] table; ... } ... }public class Thread implements Runnable { ... ThreadLocal.ThreadLocalMap threadLocals = null; ... }可以看到:
- 每個(gè)Thread中,都有一個(gè)變量ThreadLocalMap類型的變量threadLocals,threadLocals用來存放ThreadLocal;
- ThreadLocalMap中有一個(gè)變量叫做table,是一個(gè)Entry類型的數(shù)組。用于存放不同的ThreadLocal所對應(yīng)的key。一個(gè)Thread可能存在很多ThreadLocal,它們都存在table里面,一個(gè)ThreadLocal將會(huì)對應(yīng)一個(gè)table的下標(biāo);
- 每個(gè)ThreadLocal被初始化的時(shí)候,都會(huì)先去初始化它內(nèi)部final類型的threadLocalHashCode。threadLocalHashCode用于確定這個(gè)ThreadLocal在Thread中變量Entry數(shù)組table的下標(biāo)。下標(biāo)的唯一性是通過nextHashCode來確保的,它是一個(gè)AtomicInteger類型變量。
- get():
/**
* 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);
}
可以看到,set方法中先嘗試拿到當(dāng)前線程的ThreadLocalMap,然后設(shè)值。如果沒有,創(chuàng)建一個(gè),并設(shè)值。
createMap:
/**
* 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);
}
創(chuàng)建ThreadLocalMap也很簡單,就是new出來,然后將引用交給當(dāng)前線程持有,這里就可以發(fā)現(xiàn),實(shí)際上,ThreadLocal中的數(shù)據(jù),其實(shí)是保存在當(dāng)前線程內(nèi)部的。
- get方法:
/**
* 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();
}
通過getMap()拿到當(dāng)前線程的ThreadLocalMap,然后從table中取出對應(yīng)的Entry,返回里面的數(shù)據(jù)即可。
{
??spa太難SEO,我的網(wǎng)站完全木有人???♀?
所以不要臉的過來 簡書 打廣告了...
[sonny的博客](http://chings.cn/article/detail/14)
歡迎光臨~~~
}