ThreadLocal 翻譯就是線(xiàn)程局部變量畦攘,就是這個(gè)變量只存在于當(dāng)前的線(xiàn)程霸妹,只存在于當(dāng)前的線(xiàn)程,那么完美解決了并發(fā)共享資源導(dǎo)致并發(fā)不安全的問(wèn)題知押。
源碼
java.lang.ThreadLocal#get
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t); // 1
if (map != null) {
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;
}
// 1 從當(dāng)前線(xiàn)程獲取一個(gè)ThreadLocalMap叹螟,threadLocals 是Thread中的一個(gè)變量鹃骂,ThreadLocalMap是Thread中的一個(gè)靜態(tài)內(nèi)部類(lèi)。
Thread 類(lèi)中的變量 threadLocals
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
ThreadLocalMap
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;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
ThreadLocalMap的Entry 類(lèi) 注釋中說(shuō)道當(dāng)entry.get() == null 代表key不再被引用罢绽,這個(gè)entry可以從table中釋放了畏线,也可以看到Entry.java繼承了WeakReference.java(弱引用)
看到Entry[]table 變量 和Entry類(lèi),可以理出來(lái) 引用關(guān)系為 Thread->ThreadLocalMap-> Entry[]->Entry-> ThreadLocal 和 Value良价。
引用概念
強(qiáng)引用
強(qiáng)引用是使用最普遍的引用寝殴。如果一個(gè)對(duì)象具有強(qiáng)引用,那垃圾回收器絕不會(huì)回收它明垢。
軟引用
如果一個(gè)對(duì)象只具有軟引用蚣常,則內(nèi)存空間充足時(shí),垃圾回收器就不會(huì)回收它痊银;如果內(nèi)存空間不足了抵蚊,就會(huì)回收這些對(duì)象的內(nèi)存。
弱引用
弱引用也是用來(lái)描述那些非必須對(duì)象溯革,但是它的強(qiáng)度比軟引用更弱一些贞绳,被弱引用關(guān)聯(lián)的對(duì)象只能生存到下一次垃圾收集發(fā)生為止。當(dāng)垃圾收集器開(kāi)始工作致稀,無(wú)論當(dāng)前內(nèi)存是否足夠熔酷,都會(huì)回收掉只被弱引用關(guān)聯(lián)的對(duì)象。在JDK 1.2版之后提供了WeakReference類(lèi)來(lái)實(shí)現(xiàn)弱引用豺裆。
public static void main(String[] args) {
WeakReferenceObject weakReferenceObject = new WeakReferenceObject();
WeakReference<WeakReferenceObject> weakReference = new WeakReference<>(weakReferenceObject);
System.out.println(weakReference.get());
System.gc();
System.out.println(weakReference.get());
weakReferenceObject = null;
System.gc();
System.out.println(weakReference.get());
}
public static class WeakReferenceObject{
@Override
protected void finalize() throws Throwable {
System.out.println("finalize ");
}
}
// output
WeakReferenceDemo$WeakReferenceObject@4d591d15
com.daxiyan.study.base.concurrent.WeakReferenceDemo$WeakReferenceObject@4d591d15
null
finalize
虛引用
虛引用顧名思義,就是形同虛設(shè)号显。與其他幾種引用都不同臭猜,虛引用并不會(huì)決定對(duì)象的生命周期。如果一個(gè)對(duì)象僅持有虛引用押蚤,那么它就和沒(méi)有任何引用一樣蔑歌,在任何時(shí)候都可能被垃圾回收器回收。
ThreadLocal的弱引用
// Entry的構(gòu)造方法中可以看出ThreadLocal 作為WeakReference的referent揽碘。那么在下一次垃圾回收時(shí)Entry中的ThreadLocal會(huì)被回收掉次屠。
內(nèi)存泄漏
這里的內(nèi)存泄漏指的是 無(wú)用對(duì)象(不再使用的對(duì)象)持續(xù)占有內(nèi)存或無(wú)用對(duì)象的內(nèi)存得不到及時(shí)釋放,從而造成內(nèi)存空間的浪費(fèi)稱(chēng)為內(nèi)存泄漏雳刺。
當(dāng)ThreadLocal變量和 Entry的Key ThreadLocal 弱引用被釋放后劫灶,但是Entry的value還沒(méi)被釋放,并且不再使用掖桦,這時(shí)就導(dǎo)致了內(nèi)存泄漏本昏。
ThreadLocal對(duì)Entry的key為null情況的優(yōu)化
java.lang.ThreadLocal.ThreadLocalMap#getEntry
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);
}
如果當(dāng)前ThreadLocal匹配不到key,那么將調(diào)用getEntryAfterMiss方法枪汪。
java.lang.ThreadLocal.ThreadLocalMap#getEntryAfterMiss
/**
* Version of getEntry method for use when key is not found in
* its direct hash slot.
*
* @param key the thread local object
* @param i the table index for key's hash code
* @param e the entry at table[i]
* @return the entry associated with key, or null if no such
*/
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) // 1 key為null涌穆,釋放Entry怔昨。
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
// 1 key為null,釋放Entry宿稀。
java.lang.ThreadLocal.ThreadLocalMap#expungeStaleEntry
/**
* Expunge a stale entry by rehashing any possibly colliding entries
* lying between staleSlot and the next null slot. This also expunges
* any other stale entries encountered before the trailing null. See
* Knuth, Section 6.4
*
* @param staleSlot index of slot known to have null key
* @return the index of the next null slot after staleSlot
* (all between staleSlot and this slot will have been checked
* for expunging).
*/
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
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;
}
可以看到當(dāng)調(diào)用get方法會(huì)觸發(fā)key為null的Entry釋放
內(nèi)存泄漏的Demo
當(dāng)threadLocal對(duì)象設(shè)為null時(shí)趁舀,value再也無(wú)法獲取到,發(fā)生了內(nèi)存泄漏祝沸,使用線(xiàn)程池確保線(xiàn)程不銷(xiāo)毀矮烹,同時(shí)保證該線(xiàn)程不再被調(diào)用ThreadLocal.get,ThreadLocal.set方法,因?yàn)檫@兩個(gè)方法中都存在 清除key為null 的Entry奋隶。
環(huán)境:java1.8
虛擬機(jī)啟動(dòng)參數(shù):-Xms64M -Xmx64M
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalMemoryLeak {
private static ExecutorService executorService = Executors.newFixedThreadPool(100);
public static void main(String[] args) throws InterruptedException, NoSuchFieldException, IllegalAccessException {
for (int i = 0; i <80 ; i++) {
// 等待垃圾回收?qǐng)?zhí)行
Thread.sleep(100);
ThreadLocal<ByteObject> threadLocal = new ThreadLocal<ByteObject>(){
@Override
protected ByteObject initialValue() {
return new ByteObject();
}
};
executorService.execute(()->{
threadLocal.get();
// 不remove將導(dǎo)致內(nèi)存溢出
//threadLocal.remove();
});
}
Thread.sleep(3000);
executorService.shutdown();
}
public static class ByteObject{
// 5MB
private byte [] bytes = new byte[5*1024*1024];
@Override
protected void finalize() throws Throwable {
System.out.println(" finalize");
}
}
}
注釋掉remove代碼擂送,控制臺(tái)會(huì)打印java.lang.OutOfMemoryError: Java heap space。
threadLocal初始化代碼 放在for循環(huán)里唯欣,for循環(huán)后不再被引用嘹吨,在垃圾回收的時(shí)候?qū)⑨尫艃?nèi)存。因?yàn)榫€(xiàn)程詞核心線(xiàn)程數(shù)100 大于需要的線(xiàn)程數(shù)80境氢,不會(huì)觸發(fā)在同一個(gè)線(xiàn)程調(diào)用get方法蟀拷,所以導(dǎo)致ByteObject不會(huì)被釋放而內(nèi)存溢出。
如果將核心線(xiàn)程池改為1萍聊,此時(shí)無(wú)需remove问芬,也不會(huì)存在內(nèi)存溢出的情況,因?yàn)橹貜?fù)調(diào)用同一個(gè)線(xiàn)程的get方法寿桨,所以也會(huì)觸發(fā)回收ByteObject此衅。
在for循環(huán)開(kāi)始初我sleep 100 毫秒,讓垃圾回收有時(shí)間進(jìn)行亭螟,否則挡鞍,即使不注釋掉remove也會(huì)導(dǎo)致內(nèi)存溢出。
使用IDEA的visualgc插件觀察
可以看到老年代一直保持在16M预烙,內(nèi)存沒(méi)有泄露墨微,所以沒(méi)有內(nèi)存溢出。
可以看到老年代一直保持在41M扁掸,由于內(nèi)存泄漏翘县,老年代一直釋放不了,導(dǎo)致了內(nèi)存溢出谴分。
總結(jié)
使用ThreadLocal的完成后锈麸,要及時(shí)調(diào)用remove方法。
參考資料
ThreadLocal (Java Platform SE 8 )
關(guān)于Java中的WeakReference
ThreadLocal源碼解讀