Multithreading
ThreadLocal
Provide thread-confined variables to isolate state within each individual thread.
Interview: Focuses on thread-confinement mechanics, use cases (database connections, transaction contexts), and preventing memory leaks in thread pools.
Concurrency bugs stem from threads sharing mutable state. The ThreadLocal class bypasses synchronization by providing thread-confined variables, ensuring each thread maintains its own isolated copy of a variable.
Core Idea
ThreadLocal allocates a separate variable instance per thread, storing it inside a map associated with the thread.
Why It Matters
Allows sharing context (like user ID or transaction context) down the call stack without passing parameters.
Interview Lens
Tests how ThreadLocal works internally and how to clean it up to prevent serious memory leaks.
Memory Leak Risk (Crucial)
ThreadLocal variables are stored inside a custom map (ThreadLocalMap) owned by each Thread object. The map keys are WeakReferences to the ThreadLocal instance, but the values are strong references.
If a thread is reused (such as in an application server thread pool) and the ThreadLocal value is not removed, the strong reference to the value remains active as long as the worker thread is alive. This causes major memory leaks.
Rule: Always callthreadLocal.remove()inside afinallyblock when the request cycle completes.
Code Walkthrough
This class demonstrates using ThreadLocal to associate unique transaction IDs with different threads.
import java.util.UUID;public class TransactionContext { private static final ThreadLocal transactionId = ThreadLocal.withInitial(() -> UUID.randomUUID().toString());
public static String getTransactionId() { return transactionId.get(); }
public static void clear() { transactionId.remove(); // Prevents memory leaks in thread pools! }
public static void executeBusinessLogic() { try { System.out.println("Processing: " + getTransactionId() + " on " + Thread.currentThread().getName()); } finally { clear(); } } }
Interview-Relevant Information
Q: How does InheritableThreadLocal differ from ThreadLocal?
Answer: InheritableThreadLocal extends ThreadLocal. When a child thread is spawned, it inherits the values of all inheritable thread-local variables set in its parent thread.
Quick Checklist
How are variables stored inside ThreadLocal? Why does it cause memory leaks in thread pools? How do you prevent leaks? If yes, you understand ThreadLocal.
Use Cases
Storing user session tokens or security credentials in web request threads.
Managing database connection objects within transaction scopes.
Common Mistakes
Neglecting to call remove() at the end of a transaction, causing memory bloat inside application servers.
Sharing a static class instance across threads inside ThreadLocal (the value itself must be thread-unique or new instance created).