Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Concurrency

The ThreadLocal class

Reference for java.lang.ThreadLocal: give each thread its own copy of a value, with initial values, InheritableThreadLocal, leaks in pools and alternatives.

A ThreadLocal<T> is a variable with a separate value for every thread. Each thread that calls get() or set() sees only its own copy, so no locking is needed. Typical uses are per-thread instances of non-thread-safe helpers (older code often used one SimpleDateFormat per thread) and passing context such as a request id down a call chain without adding parameters.

Declare a ThreadLocal as a private static final field. The field is shared; the values it holds are not.

Java
private static final ThreadLocal<StringBuilder> BUFFER =
        ThreadLocal.withInitial(StringBuilder::new);

BUFFER.get().append("text");
BUFFER.remove();

Try it

Java Each thread sees its own value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Context passing, inheritance and cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class ThreadLocal<T> {
    public ThreadLocal()
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier)
    protected T initialValue()
    public T get()
    public void set(T value)
    public void remove()
}
Member Description
withInitial(supplier) Creates a thread-local whose first get() in each thread calls the supplier.
get() Returns the current thread's value, creating it from the initial value if needed.
set(value) Sets the current thread's value.
remove() Deletes the current thread's value; the next get() recomputes the initial value.
initialValue() Protected hook for subclasses; returns null by default.

InheritableThreadLocal<T> copies the parent thread's value into a new child thread at creation time (override childValue() to transform it).

Usage notes

  • Always call remove() in thread pools. Pool threads live a long time and serve many tasks, so a value left behind leaks into the next task (a security risk with user data) and keeps objects reachable.
  • Class loader leaks: in application servers, a ThreadLocal holding an object of a webapp class can keep the whole class loader alive after undeploy.
  • Not inherited by default, and the inherited copy is a snapshot: later changes in the parent are not seen by the child.
  • Virtual threads support thread-locals, but with millions of threads each copy costs memory. Prefer passing parameters, or ScopedValue (final in Java 25), for immutable context.
  • Hidden coupling: values that appear from nowhere make code harder to test. Use them sparingly and document them.
  • Reading is cheap, but not free: it looks up a map in the current thread. Cache the value in a local variable inside hot loops.
  • A ThreadLocal is not a substitute for synchronization when threads must share data.