Java FAQ: Top Questions
52. What is ThreadLocal in Java?
ThreadLocal
in
java.lang
provides thread-local variables, where each thread has its own independent copy, avoiding synchronization for thread-confined data.
-
Usage:
Create with
ThreadLocal, set withset, get withget. -
Memory Leaks:
Must call
removeto prevent leaks in thread pools. -
Initial Value:
Use
withInitialfor default values (Java 8+). - Use Case: Per-thread context, like user sessions or transaction IDs.
