ThreadLocal is a Java utility that creates variables whose values are isolated for each thread. Every thread gets its own independent copy of the variable, so changes made by one thread are not visible to other threads.
Key Points: • ThreadLocal helps maintain thread-specific data without using synchronization. • Each thread stores and accesses its own value, eliminating thread interference. • Commonly used for database connections, user sessions, transaction contexts, and date formatting objects. • To avoid memory leaks, ThreadLocal values should be removed using remove() when they are no longer needed.
Example: In a web application, multiple user requests are processed by different threads. A ThreadLocal variable can store the current user's information so that each thread accesses only its own user data without affecting other requests.
Code Example:
public class ThreadLocalExample {
private static final ThreadLocal<String> userContext =
new ThreadLocal<>();
public static void main(String[] args) {
Runnable task = () -> {
userContext.set(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + " -> "
+ userContext.get());
userContext.remove();
};
new Thread(task, "User-1").start();
new Thread(task, "User-2").start();
}
}Interview Tip: A concise interview answer is: ThreadLocal provides thread-specific storage where each thread maintains its own independent copy of a variable. It is commonly used to store per-thread context data and avoids synchronization because threads do not share the same value.