恆玄科技BES250解決方案之雙耳連結除錯總結和原始碼分析
阿新 • • 發佈:2022-03-14
Thread有一個成員
ThreadLocal.ThreadLocalMap threadLocals = null;
在建立ThreadLocal時會建立這個物件
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中
現在相當於Thread 一對一ThreadLocalMap
而ThreadLocalMap 以ThreadLocal(的HashCode)為Key,也就是說 ThreadLocalMap 一對多 ThreadLocal,也可以有結論
Thread 一對多ThreadLocal
//ThreadLocalMap 方法 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(); }