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
remove
to prevent leaks in thread pools. -
Initial Value:
Use
withInitial
for default values (Java 8+). - Use Case: Per-thread context, like user sessions or transaction IDs.