threadLocal理解
线程与线程变量的绑定,方便线程变量的隔离
ThreadLocal数据结构
ThreadLocal数据结构图
Thread类中引用了ThreadLocalMap
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
ThreadLocal类中定义了静态类ThreadLocalMap
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
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;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
ThreadLocalMap中定义了静态类Entry
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
ThreadLocal常用方法
set、get、remove
ThreadLocal的set方法
public void set(T value) {
//获取当前线程
Thread t = Thread.currentThread();
//获取线程的threadlocals
ThreadLocalMap map = getMap(t);
if (map != null)
//map不为空则设置值
map.set(this, value);
else
//map为空创建ThreadLocalMap并赋值
createMap(t, value);
}
//获取线程的threadlocals
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//ThreadLocalMap类中放值
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
//计算该ThreadLocal对象在table数组中的下标
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
//如果保存过该唐浩然的local对象,则覆盖
if (k == key) {
e.value = value;
return;
}
//如果该Entry对应的ThreadLocal对象为空,清除脏数据后放值
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
//创建新的Entry
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
rehash方法进行数组扩容
private void rehash() {
//清除脏数据,修改size的值
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
//使用较低的阈值
if (size >= threshold - threshold / 4)
resize();
}
//遍历数组依次清理脏数据
private void expungeStaleEntries() {
Entry[] tab = table;
int len = tab.length;
for (int j = 0; j < len; j++) {
Entry e = tab[j];
if (e != null && e.get() == null)
expungeStaleEntry(j);
}
}
//清理脏数据方法
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
//将该节点置空
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();
//节点对应的key,即threadlocal对象为null,则将值也置为null,size减一
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;
}
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
//数组扩容为原来数组的两倍
int newLen = oldLen * 2;
//创建新数组
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
//该entry对应的threadLocal为null,则将对应的value也设置为null,方便GC
if (k == null) {
e.value = null; // Help the GC
} else {
//计算新数组的下标值
int h = k.threadLocalHashCode & (newLen - 1);
//如果对应的下标值已经存有数据,则继续往后查询,知道找到为null的entry
//来保存数据
while (newTab[h] != null)
h = nextIndex(h, newLen);
//保存数据
newTab[h] = e;
count++;
}
}
}
//设置新的阈值
setThreshold(newLen);
//修改size值
size = count;
//更新table数组
table = newTab;
}
//设置阈值
private void setThreshold(int len) {
//设置阈值为数组长度的2/3
threshold = len * 2 / 3;
}