ThreadLocal<>適用于什么場景?
- 每個線程都有自己的拷貝實例姻蚓,其他線程不能訪問应结。
- 方便在線程內(nèi)部傳遞吕座。
其實可以在線程內(nèi)部new一個對象來實現(xiàn)這個需求虐译,但是這樣會產(chǎn)生大量的樣板代碼,這樣ThreadLocal就應運而生了吴趴。
怎么用漆诽?來個栗子
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)部有一個成員ThreadLocal.ThreadLocalMap threadLocals厢拭,所以每個線程都有自己的map兰英,這樣就不會沖突。這個map類似HashMap供鸠,本質(zhì)是一個Entry[]畦贸,key和value都存儲在Entry里,key是ThreadLocal楞捂,value是泛型薄坏。這個map不會發(fā)生哈希碰撞。
為什么要構(gòu)建一個map寨闹,因為thread可能需要多個threadLocal胶坠,那這些threadLocal會沖突嗎?
還有會造成內(nèi)存泄露嗎鼻忠?