InheritableThreadLocal Copies At Thread Creation
InheritableThreadLocal copies the parent value at thread construction, so a thread built before the set stays empty and pools never re-copy.
Code
public class ContextCarry {
// 父线程的上下文在线程构造瞬间复制给子线程,之后互不相通
static final InheritableThreadLocal<String> TENANT = new InheritableThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
// 构造发生在 set 之前:复制到的是当时的空值
Thread early = new Thread(() ->
System.out.println("early sees: " + TENANT.get()), "early");
TENANT.set("acme");
early.start(); // 构造时没复制到 → null
Thread late = new Thread(() ->
System.out.println("late sees: " + TENANT.get()), "late");
late.start(); // 构造时已有值 → acme
// 线程池复用已构造好的线程,不会重新复制:
// 上下文随池线程滞留,这就是线程池里 ITL 传值的经典陷阱
// 需要不同复制行为时可覆写 childValue()
}
}Copy timing
InheritableThreadLocal copies the parent value at Thread construction. The early thread is built before TENANT.set(“acme”) runs, so despite being started after the set, it prints early sees: null. The late thread is constructed after the set and prints late sees: acme.
The pool trap
Worker pools construct their threads once and reuse them; the child copy only happens at that construction, so values set later never propagate into pooled threads and stale context lingers — the classic ITL-in-pool pitfall noted in the code comments.
Customizing the copy
Overriding childValue lets a subclass transform or fence the inherited value at copy time when the default same-value handoff is not what the design needs.
Interactive Tools for This Topic
FAQ
- Why does the early thread see null even though it starts after the set?
- The inheritable copy happens when the Thread object is constructed, and the early thread was built before TENANT.set ran; starting later does not re-copy.
- Why is InheritableThreadLocal risky with thread pools?
- Pooled threads are constructed once, so later sets never reach them and previous task values linger in the thread across tasks.
Report a problem with this exampleOpens a pre-filled issue on GitHub.