简介
ThreadLocal的作用是提供线程内的局部变量,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度,可以看出ThreadLocal只作用于当前线程,如果想把公共变量传递子线程,那该如何实现呢?InheritableThreadLocal
应运而生
例子
public class ThreadLocalTest {
private static InheritableThreadLocal<String> local = new InheritableThreadLocal<>();
public static void main(String[] args) {
local.set("test");
new Thread(() -> System.out.println(local.get())).start();
}
}
输出:
test
原理
InheritableThreadLocal
实现如下,可以看出它继承了ThreadLocal
,并重写了以下三个方法
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
protected T childValue(T parentValue) {
return parentValue;
}
/**
* Get the map associated with a ThreadLocal.
*
* @param t the current thread
*/
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
/**
* Create the map associated with a ThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the table.
*/
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
所以当执行local.set("test");
时,调用java.lang.ThreadLocal.set(T)
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
//第一次进来将调用该方法
createMap(t, value);
}
然后调用java.lang.InheritableThreadLocal.createMap(Thread, T)
方法,
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
并设置thread的inheritableThreadLocals
为ThreadLocalMap
,这个inheritableThreadLocals
是传播变量的关键
线程间变量传播原理
上面提到inheritableThreadLocals
是传播变量的关键,那具体如何实现的呢?
首先看下上面例子创建子线程的操作过程
创建线程
new Thread(() -> System.out.println(local.get())).start();
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
//省略上面的代码
//可以看到parent就是父类线程 main线程
Thread parent = currentThread();
//上面提到调用java.lang.InheritableThreadLocal.createMap(Thread, T)方法时设置了inheritableThreadLocals ,
//所以这里把父类的记录逐一复制至自身线程的ThreadLocal中
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}
从上面代码可以看出把父类的记录逐一复制至自身线程ThreadLocal
是通过ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
实现的
ThreadLocal.createInheritedMap
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
// 逐一复制 parentMap 的记录到子线程ThreadLocalMap 的Entry[] 数组中
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++;
}
}
}
}
总结
InheritableThreadLocal主要用于子线程创建时,需要自动继承父线程的ThreadLocal变量,方便必要信息的进一步传递。
网友评论