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官方文檔的解釋,翻譯過來大概的意思是說舵盈,ThreadLocal的作用就是為每一個(gè)線程保存一個(gè)局部變量眠副,這樣可以做到每個(gè)線程的變量能夠互相隔離,彼此不能互相訪問坝辫。其實(shí)ThreadLocal應(yīng)該叫ThreadLocalVariable更合適迫皱,所以我們也不能單單從名字上來判斷啦。
看一下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)造方法肯定不說用了粘衬。所以首先來看一下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è)方法就是通過獲得當(dāng)前線程來獲得該線程所持有的ThreadLocal對(duì)象,然后通過getMap()方法來獲得一個(gè)ThreadLocalMap對(duì)象跪腹,最后根據(jù)是否為空褂删,來決定是直接set還是先create再set
接下來是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)鍵代碼就是通過map.getEntry()來獲得一個(gè)ThreadLocalMap.Entry,然后再取出其中的值
接下來是remove()方法:
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
調(diào)用ThreadLocalMap的remove方法冲茸,來移除掉該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ì)算等,不過在此沒有再進(jìn)行深入一布的分析盖袭。這次進(jìn)行一波簡(jiǎn)單的分析失暂,一來是為了給自己掃盲,而來是讓自己對(duì)這個(gè)ThreadLocal有一個(gè)關(guān)注鳄虱。寫到這里弟塞,又去查了一下Spring框架是如何實(shí)現(xiàn)并發(fā)處理的,貌似還和這個(gè)ThreadLocal有關(guān)系拙已,哈决记!好有意思,所以會(huì)考慮再跟Spring框架結(jié)合來一波分析倍踪。
動(dòng)手實(shí)踐
我發(fā)現(xiàn)自己還真和ThreadLocal杠上了系宫。這不,結(jié)合著自己建车,自己用Java實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的ThreadLocal類笙瑟。畢竟動(dòng)手操作一下,也有助于自己對(duì)其的理解嘛癞志。
看過別人寫的代碼之后往枷,我思考想了一下如果要實(shí)現(xiàn)這個(gè)簡(jiǎn)單的ThreadLocal,哪些點(diǎn)是核心凄杯,最為重要的错洁。
想了一下,覺著線程和變量之間是一個(gè)K-V的關(guān)系戒突,通過線程K就可以獲得其變量屯碴,所以就需要用一個(gè)Map來封裝這些數(shù)據(jù)。不過還有十分重要的一點(diǎn)就是膊存,不同線程能夠?qū)υ揗ap進(jìn)行同步操作导而。
所以首先就需要聲明一個(gè)Map:
private Map<Thread, Object> valueMap = Collections.synchronizedMap(new HashMap<Thread, Object>());
注意到該Map為 synchronizedMap
。不過至于synchronizedMap
是怎樣的一個(gè)類隔崎,其實(shí)我也不懂今艺。這里就先不說啦。
實(shí)現(xiàn)ThreadLocal的set()方法:
public void set(Object newValue) {
valueMap.put(Thread.currentThread(), newValue);
}
很簡(jiǎn)單爵卒,一個(gè)put方法就搞定了虚缎。
接下來實(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中還沒有對(duì)象,則為其初始化一個(gè)值:null
public Object initialValue() {
return null;
}
接下來實(shí)現(xiàn)ThreadLocal的remove()方法:
public void remove() {
valueMap.remove(Thread.currentThread());
}
這樣一來一個(gè)簡(jiǎn)單的ThreadLocal就搞定啦
ThreadLocal在Spring中的應(yīng)用
總結(jié)了這么多ThreadLocal的作用钓株,再細(xì)細(xì)考慮一下实牡,ThreadLocal如果說要在Spring中起什么作用的話陌僵,就是利用"以空間換取時(shí)間"的方法很好了解決了線程同步訪問問題。之前我們?cè)诮鉀Q同步問題,用的是同步塊:Synchronized。Synchronized實(shí)現(xiàn)同步是"以時(shí)間換空間"的方法伤提,不過相比于這個(gè)方法,效率較低偎谁。說到ThreadLocal在Spring的應(yīng)用,將一些單例模式的bean綁定到了每一個(gè)線程上携栋,比如對(duì)于數(shù)據(jù)庫的連接搭盾、事務(wù)資源咳秉。
總結(jié)
在網(wǎng)上找了很多有關(guān)ThreadLocal在Spring中的應(yīng)用婉支,有用的不多,看完之后感覺收獲也不是太大澜建。這一塊以后在深入學(xué)習(xí)Spring的過程中也要稍加留意向挖!