下面我们来说一下ThreadLocal。我们知道,ThreadLocal是一个实现线程间资源隔离的类,ThreadLocal为变量在每个线程中都创建了一个副本,所以每个线程可以访问自己内部的副本变量,不同线程之间不会互相干扰。下面我们就来看一下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();
}
ThreadLocal有一个内部类ThreadLocalMap,这个类有2个属性,一个是size,就是数组的长度,一个是threshold,就是扩容时的比例,默认是2/3。当size >= threshold时,遍历table并删除key为null的元素,如果删除后size >= threshold*3/4时,需要对table进行扩容。
再来看一下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,每次从自己线程的ThreadLocalMap里取值。我们再来看一下ThreadLocalMap这个类
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
内部维护了一个Entry数组
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
通过hashcode&(len-1)取到数组的下标值,然后判断该位置上是否有元素,如果没有直接放入,如果有,线性找到下一个位置放入,然后把size++。再来看一下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();
}
1.先通过hashcode&(len-1)找到数组的下标
2.如果entry不为null,设置entry的引用为k
3.如果k==key,则修改value值
4.如果k==null,说明k是以前的元素,则删除原来的元素,并添加新的元素进去,否则查找下一个元素的位置,重新判断k的引用是否为null
5.如果entry为null,则把entry加入到table的i位置中
6.通过cleanSomeSlots删除原来的元素,如果table中没有元素删除,则判断是否需要进行扩容
如果table中的元素数量达到阈值threshold的3/4,会进行扩容操作,下面我们来看一下resize方法
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();
if (k == null) {
e.value = null; // Help the GC
} else {
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
首先创建了一个新的table,容量为原来table大小的2倍。然后复制原来table的元素到新的table中,如果当前位置有元素,则找到下一个不为空的位置插入进去
再看一下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);
}
通过hashcode&(len-1)找到数组的下标,如果该位置不为空并且entry的key和ThreadLocal一致,则取出对应位置的元素返回,否则找到下一个位置
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;
}
下面来看一下createMap方法
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
就是把自己作为key放到map里了,在getMap方法里取到当前线程的ThreadLocalMap
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
ThreadLocal就分析到这里了。
网友评论