如果对ThreadLocal不了解的,请阅读理解ThreadLocal原理分析及内存泄漏问题
ThreadLocal与InheritableThreadLocal都是创建线程私有变量,ThreadLocal绑定的是当前线程,如果希望当前线程的ThreadLocal能够被子线程使用,那么我们需要使用InheritableThreadLocal。
简介:
InheritableThreadLocal类的实现非常简单,直接继承了ThreadLocal类,并重写类其中的三个方法。源码如下:
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
// 该函数在父线程创建子线程,向子线程复制InheritableThreadLocal变量时使用,后面原理时候会提到
protected T childValue(T parentValue) {
return parentValue;
}
// 从Thread类中的inheritableThreadLocals变量中获取ThreadLocalMap。不再使用threadLocals变量
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
// 赋值的时候给Thread类中的inheritableThreadLocals变量初始化。不再使用threadLocals变量。
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
原理分析
如此简单,如何实现当前线程的私有变量能够被子线程访问呢?
通过跟踪Thread的构造方法,我们发现只要父线程在构造子线程(调用new Thread())的时候inheritableThreadLocals变量不为空。新生成的子线程会通过ThreadLocal.createInheritedMap方法将父线程inheritableThreadLocals变量有的对象复制到子线程的inheritableThreadLocals变量上。这样就完成了线程间变量的继承与传递。
Thread类构造函数最终都会调用init()方法,源码如下:
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;
// 当前线程为调用new Thread()线程的父线程
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);
// 当父线程的inheritableThreadLocals 不为空的时候,会调用 ThreadLocal.createInheritedMap方法
// 传入的是当前线程(new Thread()线程的父线程)的inheritableThreadLocals变量创建为子线程的inheritableThreadLocals。
// 这样子线程就拥有了父线程的线程私有变量
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();
}
使用示例
public class InheritableThreadLocalDemo {
private static final ThreadLocal<Integer> THREAD_LOCAL = new ThreadLocal<>();
private static final InheritableThreadLocal<Integer> INHERITABLE_THREAD_LOCAL = new InheritableThreadLocal<>();
private static class DemoThread extends Thread {
@Override
public void run() {
System.out.println(THREAD_LOCAL.get());
System.out.println(INHERITABLE_THREAD_LOCAL.get());
}
}
public static void main(String[] args) {
THREAD_LOCAL.set(123);
INHERITABLE_THREAD_LOCAL.set(123);
new DemoThread().start();
THREAD_LOCAL.remove();
INHERITABLE_THREAD_LOCAL.remove();
}
}
Output:
null
123