Skip to content
Tutorials Center
My learning

Topics

Lesson 138 of 201 ยท Concurrency

ThreadLocal and ScopedValue

Learn Java ThreadLocal for per-thread state, why it leaks in thread pools, how InheritableThreadLocal behaves, and how ScopedValue (final in Java 25) replaces it safely.

Most of the trouble in multithreaded code comes from shared state: two threads touching the same variable. There is a second, quieter problem: data that is naturally per-thread or per-request, such as "who is the logged-in user for this request?" or "which transaction am I in?". Passing such values through every method signature clutters the code, and a static variable would be shared by all threads.

Java has a tool for exactly this: ThreadLocal. Each thread that uses a ThreadLocal sees its own, independent copy of the value. It has been around since Java 1.2 and is used all over frameworks, but it also has sharp edges: leaks in thread pools, copies that multiply with millions of virtual threads, and values you can change from anywhere. Java 25 finalized a modern alternative, ScopedValue, that fixes those problems. This lesson teaches both, and when to choose which.

ThreadLocal: one variable, one copy per thread

Think of a ThreadLocal<T> as a hidden map from thread to value. get() and set() look up the entry for the current thread, so two threads using the same ThreadLocal object never see each other's values.

Java Each thread has its own copy

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.

Both threads did 1,000 increments on what looks like one variable, and neither lost an update, as it would with a shared int (see Synchronization). The main thread's copy was untouched by either of them. ThreadLocal.withInitial(supplier) provides the starting value for each thread the first time it calls get().

The classic use: objects that are not thread-safe

Some classes are expensive to create and unsafe to share. SimpleDateFormat is the famous example: it keeps parsing state inside, so two threads using one instance corrupt each other's results. A ThreadLocal gives each thread a private instance that is created once and reused, without any locking. (Today you would use the thread-safe DateTimeFormatter instead, see Dates and Times. The pattern still applies to other non-thread-safe helpers, such as a MessageDigest or a reusable buffer.)

Java A private helper per thread

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.

Three threads made 300 calls but only three buffers were ever created. That is the trade you buy with ThreadLocal: one object per thread instead of one per call.

The pitfall: thread pools and leftover values

A ThreadLocal value lives as long as the thread does (or until you call remove()). That is harmless for a thread that ends after one task, but pool threads (Executors and Thread Pools) are reused for hundreds of tasks. If task 1 stores something and doesn't clean up, task 2 running on the same thread can read it.

sequenceDiagram
    participant T1 as Task 1 (user Ada)
    participant W as Pool thread (ThreadLocal slot)
    participant T2 as Task 2 (user Grace)
    T1->>W: set("Ada")
    T1->>T1: finishes (forgets remove)
    Note over W: "Ada" is still stored
    T2->>W: get()
    W-->>T2: "Ada" (wrong user!)

A pool thread outlives its tasks, and so does anything left in its ThreadLocal.

This is not a harmless glitch. It has caused real security bugs, where one user saw another user's data. Watch it happen with a pool of one thread so the reuse is guaranteed:

Java A leak between tasks, and the fix

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.

Whenever you set a value for the duration of a unit of work, wrap the work in try/finally and call remove(). Setting the value to null is not the same: the entry stays in the thread's map. Web frameworks that use ThreadLocal internally (for security context or transactions) clear it in a filter or interceptor for this exact reason.

More ThreadLocal behaviors to know

  • InheritableThreadLocal gives a new thread a copy of its parent's value at the moment the child is created. Later changes don't propagate in either direction. Thread pools create their threads lazily, so a pool thread may inherit a stale value from whoever happened to trigger its creation.
  • Memory. A thread keeps its map alive, so large objects stored in a ThreadLocal stay reachable as long as the thread lives. In an application server that reloads classes, a leaked ThreadLocal can pin an entire old class loader in memory.
  • Virtual threads (Virtual Threads and Structured Concurrency) support ThreadLocal, but you may have a million of them, and each one would get its own copy. Caching a heavy object per thread is a poor idea there; prefer a pool or an explicitly passed object.
  • Hidden coupling. A method that calls USER.get() has an invisible dependency on someone having called set() earlier. Reading the code, nothing tells you.
  • Mutability. Any code on the thread can call set(), so a deep helper method can change the value that the rest of the request sees.

ScopedValue: sharing data for a limited time

ScopedValue<T> (final in Java 25) is built for the "current request" use case. Instead of setting a value and hoping to clean up, you bind a value for the duration of a block of code. Everything called from inside the block, however deep, can read it. When the block ends, the binding is gone automatically. No remove(), no finally.

flowchart TD
    A["ScopedValue.where(USER, 'Ada').run(...)"] --> B["handleRequest()<br/>USER.get() is Ada"]
    B --> C["loadProfile()<br/>USER.get() is Ada"]
    B --> D["ScopedValue.where(USER, 'Grace').run(...)<br/>USER.get() is Grace"]
    D --> E["audit()<br/>USER.get() is Grace"]
    A --> F["After run(): USER is unbound"]

A binding exists only inside the call, can be shadowed by an inner binding, and vanishes when the call returns.

Java Binding a value for a scope

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.

The important differences from ThreadLocal:

ThreadLocal ScopedValue
Value changes anyone can set() it at any time immutable inside a scope; only re-bound by a nested where
Lifetime until remove() or the thread dies exactly the dynamic extent of run/call
Cleanup your job (finally { remove(); }) automatic
Cost with many threads one map entry per thread a cheap, immutable binding that child tasks can share
Reading get() returns the initial value if unset get() throws if unbound; isBound(), orElse()

where(key, value) returns a carrier; chain several where calls to bind several values, then finish with run(Runnable) (no result) or call(Callable)/get(Supplier) (returns a value):

Java Several bindings and a result

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.

Scoped values and threads

A ScopedValue binding belongs to the thread that created it. A plain new Thread(...) started inside the scope does not see it: the new thread has no binding. The binding is passed on to child threads only by structured concurrency (StructuredTaskScope, a preview API in Java 25), which guarantees that the children finish before the scope ends. That rule is the whole point: a value can never outlive the block that bound it, so it can never leak.

Java A new thread starts with no binding

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.

Which one should I use?

  • New code that passes context down a call chain (current user, request id, tenant, deadline): use ScopedValue. It is safer and cheaper, especially with virtual threads.
  • Caching a non-thread-safe helper per thread with a modest number of long-lived platform threads: ThreadLocal is still fine. Consider whether a simple object pool or creating the helper where needed is clearer.
  • Existing frameworks (Spring's security context, logging MDC, transaction managers) still use ThreadLocal internally. You don't need to rewrite them, but you do need to understand why their cleanup filters exist.
  • A value that changes during the request must stay a ThreadLocal, or better, become an explicit object you pass around. A ScopedValue cannot be modified (a mutable object stored in it can, but then you are sharing mutable state again).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two threads use the same static ThreadLocal<Integer> COUNTER. Thread A calls COUNTER.set(10). What does thread B see on its first COUNTER.get()?

    Each thread has its own copy. B's copy starts from the ThreadLocal's initial value and is unaffected by A.
  2. 2. Why is it important to call remove() in a finally block when you use a ThreadLocal in tasks run by a thread pool?

    The worker thread survives between tasks and keeps its ThreadLocal map, so stale values can leak to unrelated tasks and to other users.
  3. 3. What happens when you call get() on a ScopedValue outside any where(...).run(...) block?

    An unbound ScopedValue has no value. Use isBound() or orElse(default) when a binding may be missing.
  4. 4. A ScopedValue is bound with where(...).run(...), and inside the block you start new Thread(...). Does the new thread see the binding?

    A binding is tied to the scope that created it. Only structured concurrency, which guarantees children end before the scope, passes it on.

Summary

  • ThreadLocal<T> gives each thread its own copy of a value; withInitial supplies the starting value and no locking is needed.
  • Always remove() in finally when a pool thread sets a ThreadLocal, or the value leaks into later tasks; set(null) does not remove the entry.
  • InheritableThreadLocal copies the parent's value into a new thread once, which is unreliable with pools; a ThreadLocal per virtual thread can multiply memory use.
  • ScopedValue (final in Java 25) binds an immutable value for the duration of run/call, readable from any method called inside, and unbinds automatically.
  • Inner where calls shadow the outer binding for their own block; get() fails when unbound, so use isBound() or orElse.
  • A plain thread started inside a scope does not see the binding; structured concurrency is the mechanism that passes it on safely.
  • Prefer ScopedValue for per-request context in new code, and keep ThreadLocal for per-thread caches and legacy frameworks.

Next: Timer and ScheduledExecutorService, where you'll run tasks after a delay or repeatedly.