ThreadLocal<>適用于什么場(chǎng)景?
- 每個(gè)線程都有自己的拷貝實(shí)例,其他線程不能訪問。
- 方便在線程內(nèi)部傳遞。
其實(shí)可以在線程內(nèi)部new一個(gè)對(duì)象來實(shí)現(xiàn)這個(gè)需求,但是這樣會(huì)產(chǎn)生大量的樣板代碼,這樣ThreadLocal就應(yīng)運(yùn)而生了。
怎么用?來個(gè)栗子
public class SessionHandler {
private static ThreadLocal<Session> threadLocal = ThreadLocal.withInitial(() -> null);
private static ThreadLocal<Session> another = new ThreadLocal() {
protected Session initialValue() {
return null;
}
};
public Session get() {
return threadLocal.get();
}
public void set(Session session) {
threadLocal.set(session);
}
public void remove() {
threadLocal.remove();
}
}
原理是什么?需要游向代碼深水區(qū)一探究竟。
public class ThreadLocal<T> {
protected T initialValue() {
return null;
}
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
}
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;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
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();
}
}
public class Thread implements Runnable {
ThreadLocal.ThreadLocalMap threadLocals = null;
}
原來Thread內(nèi)部有一個(gè)成員ThreadLocal.ThreadLocalMap threadLocals,所以每個(gè)線程都有自己的map,這樣就不會(huì)沖突。這個(gè)map類似HashMap,本質(zhì)是一個(gè)Entry[],key和value都存儲(chǔ)在Entry里,key是ThreadLocal,value是泛型。這個(gè)map不會(huì)發(fā)生哈希碰撞。
為什么要構(gòu)建一個(gè)map,因?yàn)閠hread可能需要多個(gè)threadLocal,那這些threadLocal會(huì)沖突嗎?
還有會(huì)造成內(nèi)存泄露嗎?