ThreadLocal provides each thread its own independent copy of a variable, so multiple threads can use what looks like a shared variable without any synchronization, because no thread ever sees another thread's value.
A web framework can store the currently authenticated user in a ThreadLocal<User> set by a filter at the start of each request, letting any downstream service or utility method access SecurityContext.getCurrentUser() without threading that value through every method signature.
private static final ThreadLocal<String> currentUser = new ThreadLocal<>();
public static void setUser(String user) {
currentUser.set(user);
}
public static String getUser() {
return currentUser.get();
}
public static void clear() {
currentUser.remove(); // essential when using thread pools
}A concise interview answer is
ThreadLocal gives each thread its own isolated copy of a variable, which is great for per-request context like the current user or a bound database session in a web application, without needing synchronization. The catch is you have to explicitly call remove() when done, especially in pooled-thread environments, or you risk stale data leaking into the next request.
Last updated: 16 July 2026
Previous question: How do you check if a Thread holds a lock or not?
Next question: What is the role of ExecutorService in the Executor Framework? What methods does it provide?