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>get()ThreadLocalThreadthreadLocalsThreadLocalMapget()ThreadLocalget
The map's keys are weak references to the ThreadLocal
- A value lives as long as its thread, unless
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.remove() - If the
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 alwaysThreadLocal , so the key never goes away and onlystatic final frees the value.remove()
The map is a simple open-addressing table, not a HashMapThreadLocal0x61c88647ThreadLocal
| API | Since | Behaviour | Best for |
|---|---|---|---|
ThreadLocal | Java 1.2 | One mutable value per thread, until removed | Per-thread caches of objects that are not thread-safe |
ThreadLocal.withInitial(supplier) | Java 8 | Creates the value on a thread's first get() | Lazily created per-thread objects |
InheritableThreadLocal | Java 1.2 | Copied into a child thread when the child is created | Context passed to threads you create yourself |
ScopedValue | Java 25 (preview from Java 21) | An immutable value bound for the duration of a method call | Request 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
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:
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
0.main created a fresh counter on each thread's firstwithInitial , so no thread could see another's count.get() - With one shared
, 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.SimpleDateFormat - This is the classic use of
: reusing an expensive object that cannot be shared. For dates specifically, the better fix isThreadLocal (Java 8), which is immutable and can be shared freely; seejava.time.format.DateTimeFormatterdate 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
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:
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
, the anonymous request sawremove() : 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.alice - With
in aremove() block, the next request sawfinally . The rule: whoever sets anull on a thread it does not own must remove it inThreadLocal , at the same level of code. Frameworks do exactly this around each request, for example for a security context or a transaction.finally is not the same asset(null) : it keeps the entry, and withremove() the nextwithInitial returns null instead of a fresh initial value.get()
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 ThreadLocalremove()
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):
remove()=false heap held after all tasks finished: about 80 MB
remove()=true heap held after all tasks finished: about 0 MB
- Without
, 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 anremove() .OutOfMemoryError - With
, nothing was held. The buffers became garbage as soon as each task ended.remove() - 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 ThreadLocalInheritableThreadLocal
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:
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
for the plain variable andnull for the inheritable one. A thread created after the value changed torequest-42 got the new value: the copy is made at construction, not when the child reads it.request-43 - The trap: the pool created its thread when the first task was submitted, while
was handling request-1, so the thread inherited request-1. Whenmain 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.main - To carry context into pooled tasks, capture it when the task is submitted and set it (and remove it) inside the task, or use
with structured concurrency, which passes bindings to the child tasks it forks.ScopedValue - 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
to make a copy.childValue
ThreadLocal and virtual threads; ScopedValue
ThreadLocalThread
- 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.
ScopedValueScopedValue.where(KEY, value).run(task)taskStructuredTaskScope
Choosing a per-thread or per-request holder
| Situation | Use |
|---|---|
| An object that is not thread-safe and is expensive to create | A thread-safe replacement if one exists; otherwise ThreadLocal.withInitial |
| Formatting dates | DateTimeFormatterThreadLocal |
| Request context on platform-thread pools | ThreadLocalremove()finally |
| Request context, Java 25 and later | |
| Context for threads you create directly | InheritableThreadLocal |
| Context for tasks in an executor | Capture at submit time and pass it to the task explicitly |
| Per-thread random numbers | ThreadLocalRandom.current()ThreadLocal |
See also