ThreadLocal
Thread-local storage is a mechanism that provides each thread with its own instance of a variable. Values stored in thread-local storage are isolated to the thread that created them, so reads and writes by one thread do not interfere with others. This supports thread safety for data that should not be shared across threads while avoiding explicit synchronization.
Implementation typically relies on a per-thread data map or a thread control block. Accessors return the current
In Java, ThreadLocal<T> provides get, set, and remove operations, with optional initialValue. In Python, threading.local creates
Common uses include per-thread caches, per-thread database connections, or per-thread parsers and context objects. It is
Thread-local data persists for the lifetime of the thread. In environments with many threads or long-lived thread
Thread-local storage is not a substitute for proper resource management across asynchronous boundaries or across thread