skip to content

How does Java's ThreadLocal work under the hood: where do values live, why are keys weak but values strong, and when are stale entries expunged?

level: middleimportance: should knowfreq 60%

answer

  1. storage sits on the other object
  2. ThreadLocal is only the key
  3. entry extends WeakReference, value field strong
  4. no reference queue
  5. cleanup piggybacks on later calls

basics

~20 s

Each Thread holds a private hash map keyed by ThreadLocal objects. Keys are weak so a dropped ThreadLocal can be collected; values stay strong so they survive. Some later operations on that thread's map expunge stale entries; the GC does not.

solid answer

~50 s

On JDK 27, and identically on 25, the value is not in the `ThreadLocal`: each `Thread` has a private `threadLocals` field holding a `ThreadLocal.ThreadLocalMap`, a linear-probing table, and `get()` looks in the current thread's map with the `ThreadLocal` as key. Each entry is a `WeakReference` to the key plus a strong `value` field. The weak key stops the map alone from pinning a dropped `ThreadLocal`; the value must be strong because the map is often its only holder. After a GC clears a key, the value stays reachable and no reference queue reports it, so cleanup is a side effect of later calls on that thread: a `get()` that misses its first slot, a `set()` that inserts or meets a stale slot, a `remove()` of a present key, and the sweep before a resize. A `static` key does not go stale, so pooled threads still need `remove()`.

code

java · 20 lines
java
import java.lang.ref.WeakReference;

public class StaleEntryDemo {
    public static void main(String[] args) throws InterruptedException {
        ThreadLocal<byte[]> key = new ThreadLocal<>();
        byte[] value = new byte[1024];
        key.set(value);

        WeakReference<ThreadLocal<byte[]>> weakKey = new WeakReference<>(key);
        WeakReference<byte[]> weakValue = new WeakReference<>(value);
        key = null;
        value = null;

        System.gc();
        Thread.sleep(100);

        System.out.println("key collected:   " + (weakKey.get() == null));
        System.out.println("value collected: " + (weakValue.get() == null));
    }
}

go deeper

for a junior

Recall that each Thread carries its own private map, the ThreadLocal is only the key, and a value on a reused thread needs remove() when you are done with it.

for a middle

Explain the chain from thread to map to entry, with a weak reference to the key and a strong one to the value, and name the operations that expunge stale entries.

for a senior

Read a heap dump: a pooled thread retaining values through threadLocals, either under cleared keys or under a live static key. Weak keys help only in the first case; remove() in a finally block prevents both.

for a principal

Decide where per-thread state is allowed: each variable costs an entry on every thread that touches it, pools need cleanup discipline, and for one-way context a team may prefer scoped values, final since JDK 25.

## Where the value actually lives A **`ThreadLocal`** object does not hold your value: it acts as a key. The storage is on the thread. `java.lang.Thread` has a private field `threadLocals` of type `ThreadLocal.ThreadLocalMap`, and a second private field, `inheritableThreadLocals`, used by `InheritableThreadLocal`. `get()` takes `Thread.currentThread()`, reads that thread's map and looks up an entry using `this` as the key. If there is no entry, it calls `initialValue()` and stores the result, so reading an unset variable adds an entry, even for a `null` value. The map itself is created lazily, for its first entry. Because the public `get()`, `set()` and `remove()` touch only the current thread's map, they need no lock. The map's logic comes from `ThreadLocal.java`, which is byte-identical in JDK 25 and JDK 27, and the two `Thread` fields are declared the same way in both. ## The map is a linear-probing table `ThreadLocalMap` is a package-private static nested class, not a `java.util.Map`. - It stores an `Entry[]` table with an initial capacity of 16, always a power of two. - The slot is `threadLocalHashCode & (length - 1)`. That hash is a private per-instance field, not `hashCode()`: each new `ThreadLocal` takes the next multiple of `0x61c88647`, which spreads consecutively created variables across a power-of-two table. - A collision moves to the next slot (**linear probing**). There are no chains. - The resize threshold is two thirds of the length. Reaching it on an insert whose own scan removed nothing triggers a full sweep, and the table doubles if `size >= threshold - threshold / 4` still holds. ## Why the key is weak and the value strong An entry is `Entry extends WeakReference<ThreadLocal<?>>` with one extra field, `Object value`. | Reference | Strength | Reason | |---|---|---| | Thread to map to entry | strong | the thread owns its map | | Entry to `ThreadLocal` key | **weak** | the map alone must not pin a variable the program has dropped | | Entry to value | **strong** | the map is often the only holder, so a weak value could vanish between `set()` and `get()` | The source comment says: "To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys." With strong keys, a long-lived thread that touched many short-lived `ThreadLocal` instances would keep every one of them for its whole life. ## What the weak key does not fix - **The value stays.** Once a GC clears a key, the entry is **stale**: key gone, value still strongly reachable from the thread. - **A `static` key does not go stale.** The Javadoc says instances are typically `private static` fields, and such a key stays strongly reachable while its class is loaded. So on a pooled thread that keeps its thread-locals, the value stays until `remove()`, an overwriting `set()` or the thread's end: the classic pool leak. - **A value can pin its own key.** If the value references the `ThreadLocal`, directly or through a chain, the key stays strongly reachable from the thread and is never cleared. A class loader makes one such chain: a value's class leads to its loader, and that loader to the class holding the key, when they share one. ## When stale entries are expunged The class comment is blunt: "since reference queues are not used, stale entries are guaranteed to be removed only when the table starts running out of space." The GC only clears the reference. Removal is ordinary Java code, run by the owning thread as a side effect of later calls. | Operation | Private method | What gets cleaned | |---|---|---| | `get()`, direct hit | `getEntry` | nothing | | `get()`, first slot misses | `getEntryAfterMiss` | stale entries on the probe path | | `set()`, overwrites its key before meeting a stale slot | `set` | nothing | | `set()`, meets a stale slot | `replaceStaleEntry` | the slot is reused and the run cleaned | | `set()`, inserts a new entry | `cleanSomeSlots` | a logarithmic scan, extended when it finds one | | `remove()`, key present | `expungeStaleEntry` | its own entry and stale entries later in its run | | Size reaches the threshold | `rehash`, `expungeStaleEntries` | the whole table | | Thread terminates | `clearReferences` in `Thread` | the map is dropped whole | `expungeStaleEntry` sets the value and the slot to `null`, then rehashes the following entries up to the next empty slot, because linear probing cannot tolerate a hole inside a run. The life of one abandoned value therefore runs in this order: 1. `set()` stores an entry on the thread. 2. The program drops its last strong reference to the `ThreadLocal`. 3. A GC clears the weak key and leaves the value alone. 4. A later operation on that same thread reaches the slot and nulls the value. 5. A later GC reclaims the value, if nothing else refers to it. If no such operation comes, step 4 never happens. You can see this on JDK 27.0.1 and 25.0.3 with reflective access: after a forced GC the key is gone and the value is not, 100 direct-hit `get()` calls on another variable change nothing, and one `set()` of a new variable still leaves that single stale entry, because its `cleanSomeSlots` scan covers only a few cells. With four to eight consecutively created keys dropped, one `set()` clears them all on a 16-slot table. ## Virtual threads Each virtual thread uses its own map, since `Thread.currentThread()` returns the virtual thread, and JEP 444 advises using thread locals "only after careful consideration" because virtual threads can be very numerous.

  • Why does ThreadLocal use its own threadLocalHashCode instead of Object.hashCode()?
    Each new `ThreadLocal` takes the next multiple of `0x61c88647` from a static counter. The source says this eliminates collisions in the common case where consecutively constructed variables are used by the same threads, and produces near-optimally spread values for a power-of-two table, while staying well-behaved otherwise.
  • What can keep a ThreadLocal key from ever being cleared after the program drops it?
    A strong path from the value back to the key. The thread strongly holds the value, so if the value references the `ThreadLocal`, directly or indirectly, the key never becomes weakly reachable. A value holding its own key survives forced GCs. A class loader chain does the same when the value's class and the key's holder share a loader.
  • Does expunging a stale ThreadLocalMap entry free the value's memory immediately?
    No. `expungeStaleEntry` sets the entry's `value` and table slot to `null`, then rehashes the rest of the run, and frees nothing itself. The value becomes eligible for collection if nothing else references it, and a later GC reclaims it. Until an operation on the owning thread reaches that slot or the thread ends, the value stays, and another thread cannot force an expunge through the public API.
  • Does a virtual thread share its carrier's ThreadLocal values?
    No. `Thread.currentThread()` returns the virtual thread, and its own map is used. JEP 444 states that thread-local variables of the carrier are unavailable to the virtual thread, and vice versa. Each virtual thread therefore pays for its own map, one reason that JEP advises using thread locals only after careful consideration.

  • ThreadLocal keeps its values in an internal map keyed by Thread.
  • Weak keys mean a ThreadLocal cannot leak memory.
  • The garbage collector removes stale ThreadLocalMap entries and their values by itself.
  • Every ThreadLocal.get() call cleans up stale entries in the map.
  • ThreadLocal values are held weakly, so a value can vanish if nothing else references it.
  • A static ThreadLocal's entry goes stale as soon as the task finishes.

ThreadLocal
Java 1.2
ThreadLocal.remove
Java 1.5
java.lang.ref.WeakReference
Java 1.2

Assumes JDK 27; ThreadLocal.java is byte-identical in JDK 25, so these internals hold at both.

context