國(guó)土局網(wǎng)站建設(shè)制度制作鏈接的小程序
- ThreadLocal
- ThreadLocalMap
- get
- set
- remove
- 內(nèi)存泄漏
- key用強(qiáng)/弱引用
- entry繼承了弱引用
ThreadLocal
-
一個(gè)對(duì)象的所有線程會(huì)共享其全局變量——>線程不安全
解決方式:
方式一:同步機(jī)制,加鎖(時(shí)間換空間)
方式二:ThreadLocal在每個(gè)線程中都創(chuàng)建了一個(gè)變量的副本,線程各自訪問(wèn)自己的副本變量,則不存在變量共享問(wèn)題。(空間換時(shí)間)變量與線程的關(guān)系private static,所以ThreadLocal與線程的關(guān)系private static
eg:session -
同一個(gè)線程內(nèi)多個(gè)函數(shù)/組件間公共變量傳遞復(fù)雜,降低了多模塊間的耦合度。關(guān)聯(lián)線程和線程上下文
ThreadLocalMap
每一個(gè)thread都有一個(gè)threadLocalMap變量,key=threadLocal value=值
(一個(gè)thread可以有多個(gè)threadLocal)
public class Thread implements Runnable {//存儲(chǔ)與此線程相關(guān)的threadLocal,值由threadLocal維護(hù)ThreadLocal.ThreadLocalMap threadLocals;
}
jdk1.7的實(shí)現(xiàn)方式為每一個(gè)threadLocal都有一個(gè)threadLocalMap變量,key=threadID value=值
- 儲(chǔ)存的entry減少,之前由thread數(shù)量決定,現(xiàn)在由threadLocal決定
- thread銷(xiāo)毀對(duì)應(yīng)的threadLocalMap也銷(xiāo)毀。threadLocalMap的生命周期=線程的生命周期,內(nèi)存使用減少
get
private T get(Thread t) {ThreadLocalMap map = getMap(t);if (map != null) {if (map == ThreadLocalMap.NOT_SUPPORTED) {return initialValue();} else {//根據(jù)ThreadLocalHash計(jì)算index,取得Entry ThreadLocalMap.Entry e = map.getEntry(this);if (e != null) {@SuppressWarnings("unchecked")T result = (T) e.value;return result;}}}return setInitialValue(t);
}private T setInitialValue(Thread t) {T value = initialValue();ThreadLocalMap map = getMap(t);assert map != ThreadLocalMap.NOT_SUPPORTED;if (map != null) {map.set(this, value);} else {createMap(t, value);}if (this instanceof TerminatingThreadLocal<?> ttl) {TerminatingThreadLocal.register(ttl);}return value;
}
set
private void set(Thread t, T value) {ThreadLocalMap map = getMap(t);if (map == ThreadLocalMap.NOT_SUPPORTED) {throw new UnsupportedOperationException();}if (map != null) {map.set(this, value);} else {createMap(t, value);}
}//存入值
private void set(ThreadLocal<?> key, Object value) {// We don't use a fast path as with get() because it is at// least as common to use set() to create new entries as// it is to replace existing ones, in which case, a fast// path would fail more often than not.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.refersTo(key)) {e.value = value;return;}if (e.refersTo(null)) {replaceStaleEntry(key, value, i);return;}}tab[i] = new Entry(key, value);int sz = ++size;if (!cleanSomeSlots(i, sz) && sz >= threshold)rehash();
}//初始化map
void createMap(Thread t, T firstValue) {t.threadLocals = new ThreadLocalMap(this, firstValue);
}
remove
private void remove(Thread t) {ThreadLocalMap m = getMap(t);if (m != null && m != ThreadLocalMap.NOT_SUPPORTED) {m.remove(this);}
}
內(nèi)存泄漏
引用鏈:threadRef->thread->threadLocalMap<threadLocal,value>->entry->value
弱引用:如果這個(gè)對(duì)象只存在弱引用,那么在下一次GC時(shí)會(huì)被清理。
ThreadLocalMap 中使用的 key 為 ThreadLocal 的弱引用。所以如果 ThreadLocal 沒(méi)有被外部強(qiáng)引用,在GC時(shí)ThreadLocal 會(huì)被清理掉,ThreadLocalMap中使用這個(gè) ThreadLocal 的 key 也會(huì)被設(shè)為null。由于value 是強(qiáng)引用,不會(huì)被清理,依然存在,就會(huì)出現(xiàn) key 為 null 的 value,value無(wú)法訪問(wèn)。在map中value為強(qiáng)引用不會(huì)被清除,直到map被清除。然而由于threadLocalMap的生命周期=線程,線程池通常采取線程復(fù)用的方法,所以線程池中的線程很難結(jié)束。所以value可能一直無(wú)法回收。
key用強(qiáng)/弱引用
- key用強(qiáng)引用:引用ThreadLocal的對(duì)象被回收了,但threadLocalMap中還有threadLocal的強(qiáng)引用,若未手動(dòng)刪除,threadLocal不會(huì)被回收,導(dǎo)致entry內(nèi)存泄漏
- key用弱引用:引用ThreadLocal的對(duì)象被回收了,但threadLocalMap中還有threadLocal的弱引用,即使未手動(dòng)刪除,threadLocal也會(huì)被回收,導(dǎo)致value內(nèi)存泄漏
- 結(jié)論:若未手動(dòng)刪除key,都會(huì)導(dǎo)致內(nèi)存泄漏。強(qiáng)引用threadLocal不會(huì)被回收,弱引用value。 內(nèi)存泄漏與強(qiáng)/弱引用無(wú)關(guān),根本原因在于threadLocalMap的生命周期=線程。
解決方式:用完threadLocal,調(diào)用remove清除無(wú)用的entry,由于Entry繼承了弱引用類(lèi),會(huì)在下次GC時(shí)被JVM回收。get(),set(),remove(),會(huì)順便移除key=null的entry
entry繼承了弱引用
public class ThreadLocal<T> {static class ThreadLocalMap {private Entry[] table;//輕量級(jí)map,桶中存entry而非entry鏈表//Entry 繼承弱引用static class Entry extends WeakReference<ThreadLocal<?>> {/** The value associated with this ThreadLocal. */Object value;Entry(ThreadLocal<?> k, Object v) {super(k);value = v;}}}
}