ThreadLocal
ThreadLocal stores a value per thread. get and set see only the current thread's copy. It is a hidden method argument. Clean it up, or a thread pool will leak the value into the next task.
Detailed Explanation
Sometimes every call on a thread needs the same context: the current user, a transaction, a request id. Passing it through twenty methods is noisy. ThreadLocal hangs the value on the thread. SimpleDateFormat was the old example of a non-thread-safe object kept in a ThreadLocal so each thread had one.
withInitial supplies a factory. get creates the value on first use. remove drops it. remove is the method people skip. In a thread pool the thread lives forever. The next task on that thread gets the previous user's id. That is a security bug and a memory leak (the value and everything it reaches stay reachable from the worker).
Child threads do not inherit values unless you use InheritableThreadLocal, which copies the value at Thread start. That copy is shallow. Virtual threads and inheritable locals can multiply copies. Java 21 scoped values are the structured replacement: they are immutable for the call tree and do not leak onto a pooled thread after the scope.
You reach for ThreadLocal when a framework already uses it (transaction sync, MDC in logging) or when a thread-confined cache is real. You pass an explicit context object when you can; it is testable and visible. You never use ThreadLocal as a way to hide a global.
The cost of a forgotten remove in a servlet filter is the next request seeing the last user. The cost on virtual threads is a map entry per request if you do not remove. The cost of storing a large object is that object living as long as the thread. Always remove in finally at the boundary that set the value.
ThreadLocal is not a communication channel. Other threads cannot read it. That is the feature.
Code Examples
public class UserCtx {
private static final ThreadLocal<String> USER = new ThreadLocal<>();
static void runAs(String user, Runnable action) {
USER.set(user);
try {
action.run();
} finally {
USER.remove(); // required on pooled threads
}
}
public static void main(String[] args) {
runAs("ana", () -> System.out.println(USER.get())); // prints: ana
System.out.println(USER.get()); // prints: null
}
}import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class SafeFormat {
private static final ThreadLocal<DateTimeFormatter> FMT =
ThreadLocal.withInitial(() -> DateTimeFormatter.ISO_LOCAL_DATE);
public static void main(String[] args) {
System.out.println(LocalDate.of(2026, 9, 12).format(FMT.get()));
// prints: 2026-09-12
FMT.remove();
}
}Common Gotchas
Forgetting `remove` on a pool leaks context to the next task
always `finally`.
`InheritableThreadLocal` copies at start, not on later `set`
children do not see updates.
Virtual threads plus thread locals can allocate a lot
remove at the request edge.