InheritableThreadLocal for Child Thread Inheritance
What you'll learn: How to automatically pass thread-local values from parent threads to their child threads using InheritableThreadLocal.
The Limitation of ThreadLocal
Regular ThreadLocal variables are isolated to each thread—when you create a new thread, it starts with a clean slate and cannot access the parent thread's ThreadLocal values. This isolation is usually desirable, but sometimes you need child threads to inherit context from their parent.
What Is InheritableThreadLocal?
InheritableThreadLocal is a specialized subclass of ThreadLocal that automatically copies values from the parent thread to child threads at creation time. Think of it like a family heirloom: when a new thread is "born," it receives a copy of the parent's thread-local values.
How It Works
When you use InheritableThreadLocal, the JVM captures the parent thread's value at the moment Thread.start() is called, then provides that same value to the child thread. Each thread still maintains its own independent copy—changes in the child won't affect the parent, and vice versa.
InheritableThreadLocal<String> context = new InheritableThreadLocal<>();
context.set("Parent context");
System.out.println("Parent: " + context.get()); // "Parent context"
Thread child = new Thread(() -> {
System.out.println("Child inherited: " + context.get()); // "Parent context"
context.set("Child modified");
System.out.println("Child now: " + context.get()); // "Child modified"
});
child.start();
child.join();
System.out.println("Parent still: " + context.get()); // "Parent context"
When to Use It
Use InheritableThreadLocal when spawning worker threads that need access to contextual information like user IDs, security credentials, or request tracing data—but remember to call remove() in thread pools to prevent memory leaks, just like with regular ThreadLocal.
Key Takeaway: InheritableThreadLocal automatically copies thread-local values from parent to child threads at creation time, enabling context propagation while maintaining thread isolation.