Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How does ThreadLocal work internally?
Each Thread instance internally carries its own ThreadLocalMap, a specialized hash map. Calling threadLocal.set(value) or .get() from a given thread reads or writes an entry in that specific thread's map, keyed by the ThreadLocal instance itself.
private static final ThreadLocal<SimpleDateFormat> FORMATTER = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); String format(Date d) { return FORMATTER.get().format(d); } // per-thread instance
Because each thread reads and writes only its own map entry, there's no shared mutable state and therefore no need for synchronization between threads, which makes ThreadLocal a convenient way to give each thread its own independent copy of an otherwise non-thread-safe object.
The keys in ThreadLocalMap are held as weak references to the ThreadLocal itself, but the values are strong references. In a thread pool, where worker threads live indefinitely and are reused across tasks, forgetting to call remove() after use can leak memory, since the value stays reachable through the long-lived thread's map even after the ThreadLocal variable itself goes out of scope elsewhere.
More Related questions...