beginnerFoundations

What is a ThreadLocal, and when would you use one?

A ThreadLocal gives each thread its own independent copy of a variable, so reads and writes from one thread are never visible to another thread using the same ThreadLocal instance. Internally, each Thread object holds its own ThreadLocalMap, keyed by the ThreadLocal instances it has been given values for. Common use cases include carrying web request context, such as a user ID or request ID, that is set once at the entry point of a request filter and then read anywhere further down the call chain without having to pass it explicitly through every method signature; caching per-thread expensive objects like a SimpleDateFormat instance or a database connection; and carrying transaction context through a call stack. One important rule when using ThreadLocal inside a thread pool is to always call remove() in a finally block, because otherwise the value lingers on the pooled thread and leaks into whatever unrelated request is handled by that same thread next.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What is the double-checked locking pattern, and what makes it correct?← Back to all Java Concurrency & Multithreading questions