ThreadLocal介紹
先來介紹下這個類的作用。首先這個類的操作是線程安全的,主要是用來存儲線程相關的信息,存儲局部變量,實現局部變量的線程隔離。
主要方法介紹
get方法源碼
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();
}
- 這裏的邏輯比較簡單,調用getMap方法,
ThreadLocalMap getMap(Thread t) { return t.threadLocals; },
可以看到就是從Thread中取。如果不爲null,則根據本身實例this,從ThreadLocalMap獲取值 - 如果爲空,則調用setInitialValue方法。
setInitialValue方法源碼
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); }
新建一個ThreadLocalMap
set方法源碼
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
- 這裏也沒啥好說的
最關鍵的ThreadLocalMap內部類
我們之前有過看HashMap的經歷之後,看這個源碼就比較簡單了,但是注意剛開始我是以爲和HashMap的實現一樣,但實際上不是。先來看下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;
}
}
- 這裏涉及到了WeakReference弱引用。弱引用是指如果這個對象沒有被強引用的話,那麼發生gc的時候會進行回收。另外弱引用還有ReferenceQueue會存放弱引用gc後的對象值。具體可另外閱讀。
- 還有一點注意到沒有,這裏沒有使用鏈表的方式,那麼是如何來處理Hash碰撞的呢?
再從構造方法開始入手:
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
// private static final int INITIAL_CAPACITY = 16;
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
- 其中threadLocal的threadLocalHashCode只是爲了讓hashCode索引更加的平均,具體什麼算法原理目前不知。
- 我們可以看到初始容量是16,閾值爲
private void setThreshold(int len) { threshold = len * 2 / 3; }
在這中沒有可以設置容量或閾值的構造方法 - 這裏還有一個構造方式參數是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);
}
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;
}
- 在這裏我們可以解除之前的疑惑,即這是如何解決Hash衝突的,其實使用的是開放尋址法,我們可以看下
private static int nextIndex(int i, int len) { return ((i + 1 < len) ? i + 1 : 0); }
方法 - 這裏還剩下的一個疑問是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;
}
- 這段方法剛開始原理懂,但是摸不清楚,原因是我從getEntryAfterMiss進來的,摸不透什麼時候key會爲null。
- 這個方法可以從remove方法開始閱讀,其實就是移除當前對象,並對之後到下一個null之前的對象進行hash重定位
set方法源碼
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)]) {
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();
}
- 這裏的邏輯也比較的簡單,主要不清楚的方法是replaceStaleEntry方法和rehash方法。
- replaceStaleEntry的源碼我們就不分析了,主要功能就是用來創建或替換一個
- rehash方法源碼中包含expungeStaleEntries方法和resize方法。
今日總結
今天觀看了ThreadLocal的源碼,雖然裏面有很多方法並沒有記錄下來,但是主體思想大概已經瞭解。這裏注意爲了避免發生內存溢出,需要在使用完成後remove掉,雖然Entry是弱引用,但是ThreadLocal是強引用,所以如果不主動remove掉會造成內存溢出。