ThreadLocal

A ThreadLocal variable holds a separate value for every thread that uses it. That is useful for per-request context such as the current user, and for objects that must not be shared between threads. It also causes classic server bugs when threads are reused. This page explains where the values are really stored, then shows the per-thread fix for a thread-unsafe class, data and memory leaking between pooled tasks, the inheritance trap, and the newer alternative.

Contents

Where a ThreadLocal keeps its values

A ThreadLocal<T> (Java 1.2) looks like a variable, but get() returns a different value depending on which thread calls it. The values are not stored in the ThreadLocal object at all. Every Thread object has a field, threadLocals, holding a small hash map private to that thread, a ThreadLocalMap. get() looks up the current thread's map, using the ThreadLocal object as the key. Because only the owning thread ever touches its map, no locking is needed, and a get costs a field read and a hash lookup.

The map's keys are weak references to the ThreadLocal objects, but its values are ordinary strong references. That detail explains the memory behaviour:

  • A value lives as long as its thread, unless remove() is called. For a short-lived thread that is harmless. For a pool thread that runs for days, a value set by one task stays reachable after the task ends.
  • If the ThreadLocal object itself becomes unreachable, its entry's key is cleared by the garbage collector, but the value stays until the map happens to clean up stale entries during later operations. In practice, ThreadLocal fields are almost always static final, so the key never goes away and only remove() frees the value.

The map is a simple open-addressing table, not a HashMap. Each ThreadLocal gets a fixed hash code when it is created, by adding the constant 0x61c88647 to a global counter; that step spreads consecutive codes evenly over a power-of-two table, so collisions are rare and are resolved by trying the next slot. Methods on the map also clean up stale entries whose keys have been collected as they pass over them, which is why the cleanup of an unreachable ThreadLocal happens eventually but at no predictable time.

Per-thread and per-scope value holders
APISinceBehaviourBest for
ThreadLocalJava 1.2One mutable value per thread, until removedPer-thread caches of objects that are not thread-safe
ThreadLocal.withInitial(supplier)Java 8Creates the value on a thread's first get()Lazily created per-thread objects
InheritableThreadLocalJava 1.2Copied into a child thread when the child is createdContext passed to threads you create yourself
ScopedValueJava 25 (preview from Java 21)An immutable value bound for the duration of a method callRequest context, especially with virtual threads

All programs on this page ran on JDK 21.

One value per thread, and a thread-unsafe class made safe

The first part counts calls per thread to show that each thread has its own copy. The second part uses SimpleDateFormat, which keeps intermediate parsing state in its fields and is not thread-safe. Four threads parse two different dates 20,000 times each, first sharing one formatter and then using one formatter per thread.

Java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class PerThread {

    // Each thread gets its own counter, created on first access
    static final ThreadLocal<int[]> CALLS = ThreadLocal.withInitial(() -> new int[1]);

    static void handle() {
        CALLS.get()[0]++;
    }

    static SimpleDateFormat newFormat() {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        f.setTimeZone(TimeZone.getTimeZone("UTC"));
        return f;
    }

    static final SimpleDateFormat SHARED = newFormat();          // not thread-safe
    static final ThreadLocal<SimpleDateFormat> PER_THREAD = ThreadLocal.withInitial(
            PerThread::newFormat);

    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                handle();
            }
            System.out.println("thread A sees " + CALLS.get()[0] + " calls");
        });
        Thread b = new Thread(() -> {
            handle();
            System.out.println("thread B sees " + CALLS.get()[0] + " call");
        });
        a.start();
        a.join();
        b.start();
        b.join();
        System.out.println("main sees " + CALLS.get()[0] + " calls (its own, untouched copy)");

        System.out.println("4 threads x 20,000 parses of two different dates:");
        System.out.println("  one shared SimpleDateFormat:  wrong or failed parses > 0: "
                + (parseErrors(true) > 0));
        System.out.println("  one per thread (ThreadLocal): wrong or failed parses = "
                + parseErrors(false));
    }

    // Parses "2024-01-15" and "1999-12-31" concurrently and counts wrong results
    static int parseErrors(boolean shared) throws InterruptedException {
        AtomicInteger errors = new AtomicInteger();
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            for (int t = 0; t < 4; t++) {
                String text = t % 2 == 0 ? "2024-01-15" : "1999-12-31";
                pool.submit(() -> {
                    SimpleDateFormat f = shared ? SHARED : PER_THREAD.get();
                    for (int i = 0; i < 20000; i++) {
                        try {
                            if (!f.format(f.parse(text)).equals(text)) {
                                errors.incrementAndGet();
                            }
                        } catch (ParseException | RuntimeException e) {
                            errors.incrementAndGet();
                        }
                    }
                });
            }
        }
        return errors.get();
    }
}

Output:

Output
thread A sees 3 calls
thread B sees 1 call
main sees 0 calls (its own, untouched copy)
4 threads x 20,000 parses of two different dates:
  one shared SimpleDateFormat:  wrong or failed parses > 0: true
  one per thread (ThreadLocal): wrong or failed parses = 0
  • Thread A saw 3 calls, thread B 1, and main 0. withInitial created a fresh counter on each thread's first get(), so no thread could see another's count.
  • With one shared SimpleDateFormat, some parses returned a wrong date or threw an exception, because two threads overwrote each other's state inside the object. How many fail varies between runs, so the program prints only whether any did. With a formatter per thread, all 80,000 parses were correct.
  • This is the classic use of ThreadLocal: reusing an expensive object that cannot be shared. For dates specifically, the better fix is java.time.format.DateTimeFormatter (Java 8), which is immutable and can be shared freely; see date and time.

Values leaking between pooled tasks

A web server runs each request on a pool thread and often stores the current user in a ThreadLocal so that deep code can read it without passing it around. A single-thread pool makes the reuse of the same thread certain. The second request in each pair has no user of its own.

Java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class PoolLeak {

    static final ThreadLocal<String> USER = new ThreadLocal<>();

    // A "request handler" that sets the current user but forgets to clear it
    static String handleRequest(String user, boolean cleanUp) {
        if (user != null) {
            USER.set(user);
        }
        try {
            return "request sees user = " + USER.get();
        } finally {
            if (cleanUp) {
                USER.remove();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();    // one reused thread

        System.out.println("without remove():");
        System.out.println("  " + pool.submit(() -> handleRequest("alice", false)).get());
        Future<String> anon = pool.submit(() -> handleRequest(null, false));
        System.out.println("  " + anon.get() + "   <- leaked from the previous request");

        System.out.println("with remove() in finally:");
        System.out.println("  " + pool.submit(() -> handleRequest("bob", true)).get());
        System.out.println("  " + pool.submit(() -> handleRequest(null, true)).get());
        pool.shutdown();
    }
}

Output:

Output
without remove():
  request sees user = alice
  request sees user = alice   <- leaked from the previous request
with remove() in finally:
  request sees user = bob
  request sees user = null
  • Without remove(), the anonymous request saw alice: the value set by the previous request was still in the pool thread's map. In a real server, that means one user's request running with another user's identity or permissions.
  • With remove() in a finally block, the next request saw null. The rule: whoever sets a ThreadLocal on a thread it does not own must remove it in finally, at the same level of code. Frameworks do exactly this around each request, for example for a security context or a transaction.
  • set(null) is not the same as remove(): it keeps the entry, and with withInitial the next get() returns null instead of a fresh initial value.

Memory held by pool threads

The same mistake also holds memory. Eight tasks run on a pool of 4 threads, and each task stores a 20 MB work buffer in a ThreadLocal. After every task has finished, the program forces garbage collection and measures how much heap is still in use, once without and once with remove().

Java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MemoryRetention {

    static final ThreadLocal<byte[]> BUFFER = new ThreadLocal<>();

    static long usedMb() {
        Runtime rt = Runtime.getRuntime();
        for (int i = 0; i < 3; i++) {
            System.gc();
        }
        return (rt.totalMemory() - rt.freeMemory()) / 1000000;
    }

    static void run(boolean remove) {
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            long before = usedMb();
            List<Future<?>> tasks = new ArrayList<>();
            for (int i = 0; i < 8; i++) {
                tasks.add(pool.submit(() -> {
                    BUFFER.set(new byte[20000000]);      // a 20 MB per-thread work buffer
                    try {
                        BUFFER.get()[0] = 1;               // "use" it
                    } finally {
                        if (remove) {
                            BUFFER.remove();
                        }
                    }
                }));
            }
            for (Future<?> f : tasks) {
                try {
                    f.get();                               // every task has finished
                } catch (InterruptedException | ExecutionException e) {
                    throw new IllegalStateException(e);
                }
            }
            long after = usedMb();
            System.out.printf("remove()=%-5s heap held after all tasks finished: about %d MB%n",
                    remove, Math.round((after - before) / 10.0) * 10);
        }
    }

    public static void main(String[] args) {
        run(false);
        run(true);
    }
}

Output (heap figures are rounded to 10 MB):

Output
remove()=false heap held after all tasks finished: about 80 MB
remove()=true  heap held after all tasks finished: about 0 MB
  • Without remove(), about 80 MB stayed reachable: one 20 MB buffer per pool thread, 4 threads, even though no task was running. The later tasks overwrote the earlier tasks' buffers, so it is one buffer per thread, not per task. A large pool, or a value that grows, turns this into an OutOfMemoryError.
  • With remove(), nothing was held. The buffers became garbage as soon as each task ended.
  • In application servers the leak can be worse: a value whose class was loaded by a web application keeps that application's class loader alive after it is undeployed, through the server's pool threads. See memory leaks for finding such leaks with a heap dump.

InheritableThreadLocal and its pool trap

A plain ThreadLocal is invisible to threads that a thread creates. InheritableThreadLocal copies the parent's value into the child at the moment the child thread is constructed. The program shows the copy, then the point in time at which it happens, then what that means for a thread pool.

Java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Inheritable {

    static final ThreadLocal<String> PLAIN = new ThreadLocal<>();
    static final InheritableThreadLocal<String> INHERITED = new InheritableThreadLocal<>();

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        PLAIN.set("request-42");
        INHERITED.set("request-42");

        Thread child = new Thread(() -> System.out.println("child sees plain=" + PLAIN.get()
                + ", inheritable=" + INHERITED.get()));
        child.start();
        child.join();

        // The value is copied once, when each child thread is created
        INHERITED.set("request-43");
        Thread late = new Thread(() -> System.out.println("new child sees " + INHERITED.get()));
        late.start();
        late.join();

        // The trap: pool threads are created once and keep what they inherited
        try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
            INHERITED.set("request-1");
            System.out.println("task for request-1 sees " + pool.submit(INHERITED::get).get());
            INHERITED.set("request-2");
            System.out.println("task for request-2 sees " + pool.submit(INHERITED::get).get()
                    + "   <- copied when the pool thread was created");
        }
    }
}

Output:

Output
child sees plain=null, inheritable=request-42
new child sees request-43
task for request-1 sees request-1
task for request-2 sees request-1   <- copied when the pool thread was created
  • The child saw null for the plain variable and request-42 for the inheritable one. A thread created after the value changed to request-43 got the new value: the copy is made at construction, not when the child reads it.
  • The trap: the pool created its thread when the first task was submitted, while main was handling request-1, so the thread inherited request-1. When main moved on to request-2, the pool thread still saw request-1, and would for the rest of its life. Inheritance does not work with pools, because pool threads are created once and reused.
  • To carry context into pooled tasks, capture it when the task is submitted and set it (and remove it) inside the task, or use ScopedValue with structured concurrency, which passes bindings to the child tasks it forks.
  • The copy is shallow by default. Parent and child share the same object, so a mutable value changed in one is changed in both. Override childValue to make a copy.

ThreadLocal and virtual threads; ScopedValue

ThreadLocal works with virtual threads, which are real Thread objects with their own maps. Two habits from the pooled world do not fit them, though:

  • Caching an expensive object per thread, like the formatter above, assumes few long-lived threads. With a new virtual thread per task, each task creates its own copy and the cache saves nothing. With a million virtual threads, it costs a million copies.
  • Pooling virtual threads to reuse their thread-local caches is against their design; they are meant to be created per task. Prefer immutable shared objects instead.

ScopedValue, final in Java 25 after previews from Java 21 (JEP 506), is the replacement for the "current request" use. A value is bound with ScopedValue.where(KEY, value).run(task) and is visible only while task runs, in that thread and in subtasks forked by a StructuredTaskScope. It cannot be changed, there is nothing to remove, and it cannot leak into the next task. See scoped values for examples.

Choosing a per-thread or per-request holder

Which tool to use
SituationUse
An object that is not thread-safe and is expensive to createA thread-safe replacement if one exists; otherwise ThreadLocal.withInitial
Formatting datesDateTimeFormatter, shared, no ThreadLocal
Request context on platform-thread poolsThreadLocal with remove() in finally
Request context, Java 25 and laterScopedValue
Context for threads you create directlyInheritableThreadLocal, never with pools
Context for tasks in an executorCapture at submit time and pass it to the task explicitly
Per-thread random numbersThreadLocalRandom.current(), which needs no ThreadLocal of your own

See also ExecutorService for pools and virtual threads.