Using InheritableThreadLocal to Access Parent ThreadLocal Values in Child Threads (Java)
This article explains how to make a child thread inherit the values stored in a parent thread's ThreadLocal by using InheritableThreadLocal, demonstrates the behavior with a runnable Java example, and details the underlying ThreadLocalMap mechanism that enables the inheritance.
To allow a child thread to obtain the values stored in a parent thread's ThreadLocal, the child must use the subclass InheritableThreadLocal, which propagates the parent’s values during thread creation.
Below is a test program that creates a parent thread, sets both a regular ThreadLocal and an InheritableThreadLocal, then starts a child thread that prints the two values.
public static void main(String[] args) throws InterruptedException {
Thread parentParent = new Thread(() -> {
ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
threadLocal.set(1);
InheritableThreadLocal<Integer> inheritableThreadLocal = new InheritableThreadLocal<>();
inheritableThreadLocal.set(2);
new Thread(() -> {
System.out.println("threadLocal=" + threadLocal.get());
System.out.println("inheritableThreadLocal=" + inheritableThreadLocal.get());
}).start();
}, "父线程");
parentParent.start();
}The program prints threadLocal=null and inheritableThreadLocal=2, showing that only the inheritable version is passed to the child.
The underlying principle is that the Thread class maintains two internal ThreadLocalMap structures. When a new thread is created via new Thread(), its constructor invokes init, which sets the flag inheritThreadLocals to true.
If inheritThreadLocals is true and the parent thread’s inheritableThreadLocals map is not null, the map is copied to the child thread’s inheritableThreadLocals. This copy is what enables the child to see the parent’s values.
Finally, note that InheritableThreadLocal overrides the getMap() method of ThreadLocal, but its get() implementation simply delegates to the standard ThreadLocal logic, so the visible difference lies in the inheritance step performed during thread creation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
