1、ThreadLocal是什麼?
顧名思義,線程級的本地變量,也就是線程之間是隔離的,不共享。適合不同線程存儲各自的上下文。webapp中應用較多。
2、ThreadLocal中的屬性和方法
private final int threadLocalHashCode = nextHashCode();
private static AtomicInteger nextHashCode = new AtomicInteger();
private static final int HASH_INCREMENT = 0x61c88647;
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
threadLocalHashCode在ThreadLocal實例化的時候就確定了,爲什麼hash增加值爲0x61c88647可參考https://www.cnblogs.com/ilellen/p/4135266.html。
initialValue
protected T initialValue() {
return null;
}
返回初始化線程副本,默認返回null。這個方法是protected的,就是讓調用者根據自己的業務邏輯去覆蓋,編寫自己的初始化邏輯。
withInitial
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
return new SuppliedThreadLocal<>(supplier);
}
static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
private final Supplier<? extends T> supplier;
SuppliedThreadLocal(Supplier<? extends T> supplier) {
this.supplier = Objects.requireNonNull(supplier);
}
@Override
protected T initialValue() {
return supplier.get();
}
}
//該接口不在ThreaLocal.java中
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
傳入一個Supplier的對象,覆蓋其get方法,本質也是編寫初始化邏輯。SuppliedThreadLocal是ThreadLocal的一個內部靜態類,並且繼承了ThreadLocal,覆蓋了原來的initialValue()方法,調用supplier.get()返回。
爲了研究接下來的幾個方法,必須先研究ThreadLocal中的內部靜態類ThreadLocalMap,因爲後面的方法都和它息息相關。
ThreadLocalMap
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;
}
}
private static final int INITIAL_CAPACITY = 16;
private Entry[] table;
private int threshold; // Default to 0
}
初始化容量、門限、Entry數組這些都和HashMap類似。
注意Entry是繼承弱引用的,弱引用ThreadLocal對象本身。由弱引用的特性可知,當ThreadLocal對象變成弱可及時(如在代碼中顯式地將ThreadLocal置null),GC會回清除掉該對象,這也是爲什麼Entry中用弱引用的原因。但是會有另外一個問題,ThreadLocal對象在僅弱可及時被清除掉了,但是當時一起傳進來的value卻還留在Entry數組中,因爲一直有強引用的存在,沒法被釋放,所以有了內存泄露的風險。關於內存泄露的問題後面專門說明。
set
public void set(T value) {
//1)
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
//3)
map.set(this, value);
else
//2)
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
//4)
if (k == key) {
e.value = value;
return;
}
//5)
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
//7)
tab[i] = new Entry(key, value);
int sz = ++size;
//8)
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
//線性探測
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
//Thread.java中的代碼
ThreadLocal.ThreadLocalMap threadLocals = null;
1)獲取當前線程的threadLocals
2)threadLocals如果爲null,創建ThreadLocalMap對象,生成Entry數組賦給table,set進來的value放到對應的Entry中
3)threadLocals如果不爲空,則根據hash值算出數組索引
4)如果索引所在Entry存放的ThreadLocal對象和本次插入的相同,更新value
5)如果索引所在Entry存放的ThreadLocal已經被清除了(弱引用),則替換失效節點
6)如果4和5都不是,則尋找下一個索引,ThreadLocal針對hash碰撞採用的線性探測法,而不是HashMap中的鏈表加紅黑樹的做法
7)直到找到某個Entry爲null,將新的key和value放入到該位置
8)清除某些失效節點
其中replaceStaleEntry、cleanSomeSlots、expungeStaleEntry具體都做了什麼,可以參考https://www.cnblogs.com/cfyrwang/p/8166369.html。
get
public T get() {
//1)
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
//3)
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal<?> k = e.get();
if (k == key)
return e;
if (k == null)
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
//2)
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);
}
1)獲取當前線程的threadLocals
2)threadLocals如果爲null,則調用setInitialValue獲取初始值(如果沒有覆蓋initialValue方法,則默認返回null),並創建線程的ThreadLocalMap對象
3)threadLocals如果不爲null,說明當前線程已經存在過ThreadLocal對象了。調用getEntry獲取TreadLocal所在的Entry,獲取value
remove
public void remove() {
//1)
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
private void remove(ThreadLocal<?> key) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
if (e.get() == key) {
//2)
e.clear();
//3)
expungeStaleEntry(i);
return;
}
}
}
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
//4)
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// Rehash until we encounter null
Entry e;
int i;
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
//Reference.java中的代碼
public void clear() {
this.referent = null;
}
1)獲取當前線程的threadLocals
2)找到對應的Entry節點,將引用的對象置null
3)清除失效的節點
4)重點就是將value置null,斷開value的強引用,Entry置null,斷開強引用
3、ThreadLocal結構
先來看個例子
public class ThreadLocalTest implements Runnable{
private static ThreadLocal<Long> threadLocalLong = new ThreadLocal<>();
private static ThreadLocal<String> threadLocalString = new ThreadLocal<String>() {
@Override
public String initialValue() {
return "hello";
}
};
@Override
public void run() {
Long value = threadLocalLong.get();
if (value == null) {
System.out.println(Thread.currentThread().getName() + " threadLocalLong init value is null");
}
threadLocalLong.set(Thread.currentThread().getId());
System.out.println(Thread.currentThread().getName() + " threadLocalLong value is " + threadLocalLong.get());
threadLocalLong.remove();
System.out.println(Thread.currentThread().getName() + " threadLocalLong value is " + threadLocalLong.get());
String string = threadLocalString.get();
System.out.println(Thread.currentThread().getName() + " threadLocalString init value is " + string);
}
public static void main(String[] args) throws InterruptedException{
for (int i = 0; i < 2; i++) {
Thread thread = new Thread(new ThreadLocalTest());
thread.start();
}
}
}
輸出爲
Thread-1 threadLocalLong init value is null
Thread-1 threadLocalLong value is 14
Thread-1 threadLocalLong value is null
Thread-1 threadLocalString init value is hello
Thread-0 threadLocalLong init value is null
Thread-0 threadLocalLong value is 13
Thread-0 threadLocalLong value is null
Thread-0 threadLocalString init value is hello
結構圖爲
每個Thread維護自己的Map,裏面存放各自線程的ThreadLocal對象,所以這也是爲什麼它能做到線程間相互隔離。
正是由於這種特性,所以ThreadLocal變量最好聲明成private static的,如果你聲明爲成員變量,那麼每new一個線程,就會多出一個ThreadLocal對象,而最終存儲在各自線程的ThreadLocalMap中,聲明爲private static的可以避免生成多餘的ThreadLocal對象。但是這樣會把ThreadLocal的聲明週期拉長,同類相同,可能會造成內存泄露。
4、內存泄露
前面說過,Entry的key是ThreadLocal對象的弱引用,當線程中把ThreadLocal對象的強引用斷開後,如置null,那麼ThreadLocal對象變成弱可及的,在下次GC時會被回收。Entry的key被回收了,但是value因爲Entry的強引用關係,會一直得不到回收,造成內存泄露。
網上看的一個圖來說明:
其中實線爲強引用,虛線爲弱引用。
如果線程遲遲得不到回收,那麼value一直就得不到回收,所以線程池中使用ThreadLocal就可能會造成內存泄露,還可能產生髒讀。
remove方法中會調用expungeStaleEntry(set和get時也會對key爲null的節點進行清除),將Entry節點及value的強引用斷開,便於下次GC回收,所以在使用的時候,最後記得調用remove方法。如
try {
threadLocal.set();
threadLocal.get();
...
} finally {
threadLocal.remove();
}
Netty中的FastThreadLocal就是這麼做的。
參考: