概述
ThreadLocal是泛型类,主要作用是存储线程间独立的变量,优势在于
1、方便线程内完成数据的存取,免去在切换上下文的过程中参数的传递;
2、不同线程间数据set和get互不影响;
下面主要通过代码分析其主要技术实现;
我们知道在set和get方法中并不需要传入线程信息,那么如何做到不同线程间存取互不干扰呢?
我们常用如下的set方式,set方法中未传入线程任何信息;
class ThreadLocalAnalyser {
ThreadLocal<String> mThreadLocal = new ThreadLocal();
public void startThreadA() throws InterruptedException {
mThreadLocal.set("被忽视");
new Thread(() -> {
mThreadLocal.set("萌萌哒");
//many steps later...
System.out.println(mThreadLocal.get());//被夸萌萌哒,happy
}, "A").start();
Thread.sleep(1000);
System.out.println(mThreadLocal.get());//被忽视了,sad
}
}
同一个ThreadLocal对象在不同的线程中赋值两次,但是获取的值却各不相同,这是如何做到的呢?
我们看看ThreadLocal的源码,先分析set;
class ThreadLocal<T>{
、、、省略若干、、、
//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);
}
//先看如何初始化存储
//可见数据存储是和Thread实例相关的,每个Thread实例都包含的ThreadLocalMap类型的变量,该变量实际存储了当前线程的数据;
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
static class ThreadLocalMap{
private static final int INITIAL_CAPACITY = 16;
private Entry[] table;
static class Entry extends WeakReference<ThreadLocal> {
Object value;
Entry(ThreadLocal k, Object v) {
super(k);
value = v;
}
}
ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];//内部使用数组存储
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
//可见数组中存储位置是和ThreadLocal实例以及数组大小相关的
table[i] = new Entry(firstKey, firstValue);
size = 1;
//设置阀值,超过此大小需要扩容
setThreshold(INITIAL_CAPACITY);
}
//如果已初始化过,则通过此方法插入数据
private void set(ThreadLocal key, Object value) {
Entry[] tab = table;
int len = tab.length;
//可见在数组未扩容时,每个ThreadLocal对象插入任意数据的初始位置是固定的
int i = key.threadLocalHashCode & (len-1);
//该位置已存储值,则i++向右遍历
for (Entry e = tab[i];e != null;e = tab[i = nextIndex(i, len)]) {
ThreadLocal k = e.get();
//是相同的ThreadLocal实例
if (k == key) {
e.value = value;
return;
}
//某个Entry被回收了
if (k == null) {
//替换失效数据
replaceStaleEntry(key, value, i);
return;
}
}
//两种case:初始位置未存储值,或存储位置已满
tab[i] = new Entry(key, value);
int sz = ++size;
//清除无效数据后,如果数组大小超出阀值,则rehash,重新排列数据位置
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
}
private final int threadLocalHashCode = nextHashCode();
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
private static AtomicInteger nextHashCode =
new AtomicInteger();
//不明觉厉的增值,目的应该是最大化减少碰撞概率
private static final int HASH_INCREMENT = 0x61c88647;
}
再看get
class ThreadLocal<T>{
、、、省略若干、、、
//get方法
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
//如果还未初始化,则先将null作为默认值存储到数组中,且返回null
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;
}
//如果已初始化
static class ThreadLocalMap{
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];
}
//坑为null或向右遍历都未找到则返回null
return null;
}
}
}
概括:
开发人员一般只使用ThreadLocal提供的set和get方法,而ThreadLocal提供存储数据的内部类ThreadLocalMap,ThreadLocalMap内部通过数组持有弱引用的ThreadLocal和Object数据;而每个Thread实例都包含独立的ThreadLocalMap引用;部分实现逻辑和list以及hashMap有异曲同工之处;
在我们使用set和get时ThreadLocal懒加载初始化Thread持有的ThreadLocalMap,而初始化是由调用所在线程决定的;ThreadLocal的身份标识threadLocalHashCode像Object.hashCode一样在与数组长度”&”后是有可能碰撞的,这时候会向右遍历插入数据,保证了效率;同时在线程被回收后,ThreadLocal也需要被回收,所以需要无时不刻的清除失效的数据;