ThreadLocal源码分析
Posted cao_null
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThreadLocal源码分析相关的知识,希望对你有一定的参考价值。
//使用泛型
public class ThreadLocal<T>
//空实现
public ThreadLocal()
public void set(T value)
Thread t = Thread.currentThread();
//ThreadLocalMap是核心对象
ThreadLocalMap map = getMap(t);
//为空则创建,否则设置value
if (map != null)
map.set(this, value);
else
createMap(t, value);
先看createMap
void createMap(Thread t, T firstValue)
t.threadLocals = new ThreadLocalMap(this, firstValue);
这里看到创建的ThreadLocalMap赋值给了Thread的threadLocals。
public
class Thread implements Runnable
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
每个线程维护一个自己的ThreadLocalMap,接下来分析ThreadLocalMap。
静态内部类
static class ThreadLocalMap
//ThreadLocal作为key采用弱引用
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;
private Entry[] table;
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);
Entry数组,始化大小为16,然后是生成散列后的位置i,这里继续分析firstKey.threadLocalHashCode。
//final修饰的int类型
private final int threadLocalHashCode = nextHashCode();
//这个值为了散列均匀,2的32次方乘以黄金分割
private static final int HASH_INCREMENT = 0x61c88647;
/**
* Returns the next hash code.
*/
//每次调用+1
private static int nextHashCode()
return nextHashCode.getAndAdd(HASH_INCREMENT);
这里第一个值就已经放入了i位置,继续看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;
//同样先计算散列位置i
int i = key.threadLocalHashCode & (len-1);
之后从i位置遍历数组
for (Entry e = tab[i];
e != null;
//nextIndex简单粗暴直接+1
e = tab[i = nextIndex(i, len)])
//从数组里获取当前元素的key
ThreadLocal<?> k = e.get();
//相等说明同一个key直接替换value
if (k == key)
e.value = value;
return;
//key是null,但是value有值,需要清空垃圾避免内存泄漏,稍后分析
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 static int nextIndex(int i, int len)
return ((i + 1 < len) ? i + 1 : 0);
//旧的Entry是垃圾数据,需要用新的数据替换
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot)
Entry[] tab = table;
int len = tab.length;
Entry e;
// Back up to check for prior stale entry in current run.
// We clean out whole runs at a time to avoid continual
// incremental rehashing due to garbage collector freeing
// up refs in bunches (i.e., whenever the collector runs).
int slotToExpunge = staleSlot;
//往staleSlot前循环,确保整个表没有泄露
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
// Find either the key or trailing null slot of run, whichever
// occurs first
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len))
ThreadLocal<?> k = e.get();
// If we find key, then we need to swap it
// with the stale entry to maintain hash table order.
// The newly stale slot, or any other stale slot
// encountered above it, can then be sent to expungeStaleEntry
// to remove or rehash all of the other entries in run.
//往后遍历找到了key则交换,保证散列顺序
if (k == key)
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
if (slotToExpunge == staleSlot)
slotToExpunge = i;
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
// If we didn't find stale entry on backward scan, the
// first stale entry seen while scanning for key is the
// first still present in the run.
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
//走到这说明没找到一样的key,直接清除替换
// If key not found, put new entry in stale slot
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
//清理
private boolean cleanSomeSlots(int i, int n)
boolean removed = false;
Entry[] tab = table;
int len = tab.length;
do
i = nextIndex(i, len);
Entry e = tab[i];
if (e != null && e.get() == null)
n = len;
removed = true;
i = expungeStaleEntry(i);
while ( (n >>>= 1) != 0);
return removed;
private int expungeStaleEntry(int staleSlot)
Entry[] tab = table;
int len = tab.length;
//先清理槽位
// expunge entry at staleSlot
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
//然后重新hash
// 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;
接着看rehash
setThreshold(INITIAL_CAPACITY);
private void setThreshold(int len)
//默认是初始长度的三分之二
threshold = len * 2 / 3;
private void rehash()
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
private void resize()
Entry[] oldTab = table;
int oldLen = oldTab.length;
//两倍扩容
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
//遍历重新hash
for (int j = 0; j < oldLen; ++j)
Entry e = oldTab[j];
if (e != null)
ThreadLocal<?> k = e.get();
if (k == null)
e.value = null; //帮助GC
else
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
//重设threshold
setThreshold(newLen);
size = count;
table = newTab;
继续分析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();
private Entry getEntry(ThreadLocal<?> key)
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
//命中就返回e
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)//如果key是空,说明泄露了,就清理
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
return null;
总结:
每个Thread持有自己的ThreadLocalMap,所以线程间数据隔离。
内存泄漏问题:
假设场景:A类调用ThreadLocal的set方法,在当前线程Thread中两条引用关系如下:强引用链:A->Thread->ThreadLocalMap->Entry->Value;弱引用链:ThreadLocal->Entry。
随着A类执行完后,引用关系结束,GC扫描把弱引用链Entry的key中ThreadLocal回收,但是value还长时间存在,直到Thread被回收,发生内存泄漏。
解决办法:虽然set等方法也会触发expungeStaleEntry等回收操作,但是原则上
使用完ThreadLocal后应该立即remove。
以上是关于ThreadLocal源码分析的主要内容,如果未能解决你的问题,请参考以下文章
ThreadLocal源码分析_02 内核(ThreadLocalMap)