InheritableThreadLocal
这个类是如何起作用的,咱们来跟一下源码:
Thread的构造函数里面只会调用一个init方法,这个init的方法有一个参数:boolean inheritThreadLocals,用于表明子线程要不要继承父线程的threadlocal;对于绝大多数的Thread的构造函数而言,这个参数是true。
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals)
复制代码
函数体:
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
}
/* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
g = parent.getThreadGroup();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
if (inheritThreadLocals && 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();
}
复制代码
如果父线程的inheritableThreadLocals不为空,则执行:
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
复制代码
因此继续跟一下源代码:
this.inheritableThreadLocals是Thread中的一个成员变量,类型为ThreadLocal.ThreadLocalMap :
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
复制代码
ThreadLocal的createInheritedMap方法:
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
复制代码
接着跟:
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++;
}
}
}
}
复制代码
如上的构造函数中,我们看到ThreadLocalMap的Entry[]数组是被重新构建了,但是每个Entry中的key还是原来父线程中的threadlocal,value是通过调用
T childValue(T parentValue) 方法来的,而这个类的实现在InheritableThreadLocal中,默认返回的还是父线程中的那个value。
因此如果要清掉value就需要,在父子线程中,对同一个InheritableThreadLocal,都调用clear,才行。
T childValue(T parentValue)的实现在TreadLocal中会抛出异常,因此线程中的ThreadLocal.ThreadLocalMap inheritableThreadLocals 变量,Entry中的key指向的是InheritableThreadLocal。
综上
我们看到,如果父线程的
ThreadLocal.ThreadLocalMap inheritableThreadLocals 变量,如果不为null,则会拷贝出一个
ThreadLocal.ThreadLocalMap对象赋值给子线程的
inheritableThreadLocals 变量。并且inheritableThreadLocals中的Entry中的key指向的是InheritableThreadLocal。
由于T childValue(T parentValue) 方法的实现在InheritableThreadLocal中,因此我们继续跟一下InheritableThreadLocal的源码:
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
protected T childValue(T parentValue) {
return parentValue;
}
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
复制代码
childValue方法跟过了,因此继续跟一下
ThreadLocalMap getMap(Thread t)和
void createMap(Thread t, T firstValue) ;
先跟一下
createMap(Thread t, T firstValue) ;
这个方法在两个地方有调用ThreadLocal#public void set(T value)和ThreadLocal#private T setInitialValue()
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
复制代码
如上,InheritableThreadLocal调用public void set(T value)方法,则
getMap(t)调用的是InheritableThreadLocal的覆盖方法
返回的是t.inheritableThreadLocals;然后如果这个map是null,则调用
createMap(t, value);调用的是InheritableThreadLocal中的覆盖方法,即建一个ThreadLocalMap赋值给线程的inheritableThreadLocals变量。
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;
}
复制代码
如上,该代码和public void set(T value)方法基本相同,此处就不在分析了。
跟一下:
ThreadLocalMap getMap(Thread t)被使用的剩余地方:
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();
}
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
复制代码
如上,比较简单就不在阐述。
至此InheritableThreadLocal的源码就算看完了
最后总结下:
如果我们使用InheritableThreadLocal来做threadlocal的话,那么InheritableThreadLocal会被存放到线程的
inheritableThreadLocals 变量中,并且当你new一个线程的时候,父线程的
ThreadLocal.ThreadLocalMap inheritableThreadLocals 变量,如果不为null,则会拷贝出一个
ThreadLocal.ThreadLocalMap对象赋值给子线程的
inheritableThreadLocals 变量。