ThreadLocal類是什么:
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).
oracle官方文檔的解釋,翻譯過(guò)來(lái)大概的意思是說(shuō),ThreadLocal的作用就是為每一個(gè)線程保存一個(gè)局部變量,這樣可以做到每個(gè)線程的變量能夠互相隔離,彼此不能互相訪問(wèn)。其實(shí)ThreadLocal應(yīng)該叫ThreadLocalVariable更合適,所以我們也不能單單從名字上來(lái)判斷啦。
看一下ThreadLocal的API:
//Creates a thread local variable.
ThreadLocal()
//Returns the value in the current thread's copy of this thread-local variable.
T get()
//Returns the current thread's "initial value" for this thread-local variable.
protected T initialValue()
//Removes the current thread's value for this thread-local variable.
void remove()
//Sets the current thread's copy of this thread-local variable to the specified value.
void set(T value)
//Creates a thread local variable.
static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier)
目前先集中精力關(guān)注前五個(gè)方法,即構(gòu)造方法,get()
initialValue()
remove()
和set(T value)
構(gòu)造方法肯定不說(shuō)用了。所以首先來(lái)看一下initialValue()方法的源碼:
protected T initialValue() {
return null;
}
這個(gè)方法是提供給繼承的子類復(fù)寫用的,一般在某些特定的業(yè)務(wù)情景下,我們需要給ThreadLocal一個(gè)初始變量。
看一下set(T value)源碼:
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()方法:
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
這個(gè)方法就是通過(guò)獲得當(dāng)前線程來(lái)獲得該線程所持有的ThreadLocal對(duì)象,然后通過(guò)getMap()方法來(lái)獲得一個(gè)ThreadLocalMap對(duì)象,最后根據(jù)是否為空,來(lái)決定是直接set還是先create再set
接下來(lái)是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();
}
關(guān)鍵代碼就是通過(guò)map.getEntry()來(lái)獲得一個(gè)ThreadLocalMap.Entry,然后再取出其中的值
接下來(lái)是remove()方法:
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
調(diào)用ThreadLocalMap的remove方法,來(lái)移除掉該ThreadLocal所對(duì)應(yīng)的局部變量
小結(jié):
有關(guān)ThreadLocal的源碼分析,進(jìn)一步會(huì)涉及到ThreadLocalMap是如何進(jìn)行set()的,如何get(),remove()的,其中會(huì)涉及到一些數(shù)據(jù)結(jié)構(gòu),比如繼承自WeakReference的Entry數(shù)組,哈希值的計(jì)算等,不過(guò)在此沒(méi)有再進(jìn)行深入一布的分析。這次進(jìn)行一波簡(jiǎn)單的分析,一來(lái)是為了給自己掃盲,而來(lái)是讓自己對(duì)這個(gè)ThreadLocal有一個(gè)關(guān)注。寫到這里,又去查了一下Spring框架是如何實(shí)現(xiàn)并發(fā)處理的,貌似還和這個(gè)ThreadLocal有關(guān)系,哈!好有意思,所以會(huì)考慮再跟Spring框架結(jié)合來(lái)一波分析。
動(dòng)手實(shí)踐
我發(fā)現(xiàn)自己還真和ThreadLocal杠上了。這不,結(jié)合著自己,自己用Java實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的ThreadLocal類。畢竟動(dòng)手操作一下,也有助于自己對(duì)其的理解嘛。
看過(guò)別人寫的代碼之后,我思考想了一下如果要實(shí)現(xiàn)這個(gè)簡(jiǎn)單的ThreadLocal,哪些點(diǎn)是核心,最為重要的。
想了一下,覺(jué)著線程和變量之間是一個(gè)K-V的關(guān)系,通過(guò)線程K就可以獲得其變量,所以就需要用一個(gè)Map來(lái)封裝這些數(shù)據(jù)。不過(guò)還有十分重要的一點(diǎn)就是,不同線程能夠?qū)υ揗ap進(jìn)行同步操作。
所以首先就需要聲明一個(gè)Map:
private Map<Thread, Object> valueMap = Collections.synchronizedMap(new HashMap<Thread, Object>());
注意到該Map為 synchronizedMap
。不過(guò)至于synchronizedMap
是怎樣的一個(gè)類,其實(shí)我也不懂。這里就先不說(shuō)啦。
實(shí)現(xiàn)ThreadLocal的set()方法:
public void set(Object newValue) {
valueMap.put(Thread.currentThread(), newValue);
}
很簡(jiǎn)單,一個(gè)put方法就搞定了。
接下來(lái)實(shí)現(xiàn)ThreadLocal的get()方法:
public Object get() {
Thread thread = Thread.currentThread();
Object o = valueMap.get(thread);
if (o == null && !valueMap.containsKey(thread)) {
o = initialValue();
valueMap.put(thread, o);
}
return o;
}
如果該線程的ThreadLocal中還沒(méi)有對(duì)象,則為其初始化一個(gè)值:null
public Object initialValue() {
return null;
}
接下來(lái)實(shí)現(xiàn)ThreadLocal的remove()方法:
public void remove() {
valueMap.remove(Thread.currentThread());
}
這樣一來(lái)一個(gè)簡(jiǎn)單的ThreadLocal就搞定啦
ThreadLocal在Spring中的應(yīng)用
總結(jié)了這么多ThreadLocal的作用,再細(xì)細(xì)考慮一下,ThreadLocal如果說(shuō)要在Spring中起什么作用的話,就是利用"以空間換取時(shí)間"的方法很好了解決了線程同步訪問(wèn)問(wèn)題。之前我們?cè)诮鉀Q同步問(wèn)題,用的是同步塊:Synchronized。Synchronized實(shí)現(xiàn)同步是"以時(shí)間換空間"的方法,不過(guò)相比于這個(gè)方法,效率較低。說(shuō)到ThreadLocal在Spring的應(yīng)用,將一些單例模式的bean綁定到了每一個(gè)線程上,比如對(duì)于數(shù)據(jù)庫(kù)的連接、事務(wù)資源。
總結(jié)
在網(wǎng)上找了很多有關(guān)ThreadLocal在Spring中的應(yīng)用,有用的不多,看完之后感覺(jué)收獲也不是太大。這一塊以后在深入學(xué)習(xí)Spring的過(guò)程中也要稍加留意!