節選jdk源碼中比較重要的方法進行分析,以下:java
public class ThreadLocal<T> { 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); } 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 void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this); } ThreadLocalMap getMap(Thread t) { return t.threadLocals; } 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; /** * 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; private int threshold; // Default to 0 /** * Set the resize threshold to maintain at worst a 2/3 load factor. */ private void setThreshold(int len) { threshold = len * 2 / 3; } private static int nextIndex(int i, int len) { return ((i + 1 < len) ? i + 1 : 0); } ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) { table = new Entry[INITIAL_CAPACITY]; int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); table[i] = new Entry(firstKey, firstValue); size = 1; setThreshold(INITIAL_CAPACITY); } 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; } 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(); if (k == key) { e.value = value; return; } if (k == null) { replaceStaleEntry(key, value, i); return; } } tab[i] = new Entry(key, value); int sz = ++size; if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); } 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) { e.clear(); expungeStaleEntry(i); return; } } } } }
能夠看到,數據結構就是每一個線程都有一個ThreadLocalMap類型的threadLocals變量來維護線程內的全部ThreadLocal實例。ThreadLocalMap並不繼承Map,底層數據結構是一個數組ThreadLocalMap.Entry[] table數組(默認大小16),以及ThreadLocalMap.Entry(注意,它並不像HashMap那樣,它並非個鏈表元素,沒有next引用),Entry的key是ThreadLocal對象,Entry在table中的位置由threadLocalHashCode決定,它在每次ThreadLocal初始化時被賦予值,每次都會增長 0x61c88647,注意:nextHashCode是一個靜態變量. 數組
<!--more-->數據結構
ThreadLocal設置與獲取值:
在設置值的時候,會現根據Thread.currentThread()即當前線程獲取其ThreadLocalMap變量,再調用ThreadLocalMap.set方法,傳入的key爲ThreadLocal對象自己。那麼存在哪裏呢?它會根據int i = key.threadLocalHashCode & (len-1);
來計算出索引,其中len爲table數組的長度,接下來就對table[i]上的Entry進行判斷,若是Entry的key=咱們傳入的key,那麼就更新它。若是Entry的key爲null(因爲Entry的key是WeakReference<ThreadLocal<?>,因此其key的生命週期與GC相關,下次GC時會被回收,從而致使null的出現),那麼就覆蓋它。不然i+1,尋找下個位置,若是找到了仍然按上述邏輯來,若是沒找到,那麼就會在數組尾部新建Entry並判斷是否須要擴容table數組(擴容因子2/3),若是須要擴容,那麼同時須要rehash操做。
在獲取值的時候,會現根據Thread.currentThread()即當前線程獲取其ThreadLocalMap變量,再調用ThreadLocalMap.getEntry方法,傳入的key爲ThreadLocal對象自己。其中會進行key.threadLocalHashCode & (table.length - 1);
計算獲取索引值i,若是table[i]==key,那麼返回,不然就會調用getEntryAfterMiss,其內部邏輯就是,循環一直對i+1並獲取索引處的Entry,若是Entry.key相等返回,若是Entry,key爲null,清除對應的值(爲防止內存泄漏的一個舉措).this
還有個remove方法:
其會清除Entry的key及對應的value線程
ThreadLocal如何保證隔離各個線程呢?
前面說了,ThreadLocal的set/get底層都是經過ThreadLocalMap來進行的,而每一個線程都有本身的ThreadLocalMap變量,經過Thread.currentThread().threadLocals來獲取。因此這樣就確保了每一個線程的ThreadLocal對其餘線程不可見。那麼我在一個線程初始化的時候拿到了另外一個線程的引用,好比在main thread new 一個 thread,那麼main thread就獲取了那個thread的引用t,此時,我經過t.threadLocals來獲取這個ThreadLocalMap並操做其中的ThreadLocal行不行?親愛的,這是不行的。因threadLocals是默認的訪問修飾,也就是說只有當前包(java.lang)狀況下可訪問.code
那爲何ThreadLocal變量會致使內存泄漏呢?
首先來回顧下Entry的代碼對象
static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }
Entry是實現了弱引用的。那麼來講說Java中有四種引用類型之弱引用
WeakReference標誌性的特色是:reference實例不會影響到被應用對象的GC回收行爲,只要對象被除WeakReference對象以外全部的對象解除引用後,該對象即可以被GC回收,只不過在被對象回收以後,reference實例想得到被應用的對象時程序會返回null繼承
但要注意的是,此處的弱引用針對的是key,而value仍然是強引用。
從前面的代碼咱們看到,set方法在碰到Entry.key==null是時會調用replaceStaleEntry,而replaceStaleEntry內部又會調用expungeStaleEntry, get方法則在碰到Entry.key==null時直接調用expungeStaleEntry。那麼咱們來看看這個expungeStaleEntry代碼:索引
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; }
能夠看到它除了釋放索引i處Entry的key,value引用以外,還會遍歷i後面的索引,只要碰到Entry.key爲null的都會進行釋放。同時會對已有不在hash定位處的Entry進行移動位置,以下降後續哈希碰撞的概率。生命週期
一言以蔽之,就是ThreadLocal自己爲防止內存泄漏做出了必定的努力,首先Entry.key爲弱引用,在ThreadLocal沒有被其餘比弱引用強的引用如強引用,軟引用引用時,下次GC時,Entry.key即ThreadLocal弱引用會被回收,可是Entry.value是強引用,須要在當前線程的任意一個get,set調用而且碰到Entry.key==null的情形下會清除對於的Entry並釋放value引用。
那麼問題來了,當咱們使用線程池的時候,萬一這該死的線程一直處理存活狀態(不斷運行不一樣的Runnable,每一個Runnable又new一個或多個ThreadLocal),並且get,set大部分時候都沒碰到Entry.key==null的情形(threadLocalHashCode & (len-1)說怪我咯),那麼就會致使內存泄漏。其實出現這樣的概率有點低,對吧?可是畢竟是存在這樣的可能性嘛,那麼如何防範呢?其實只要咱們養成一個好習慣就能夠了,那就是每次使用完ThreadLocal後,調用其remove方法便可防止內存泄漏。
本文同步發佈在自有博客-博文地址