ThreadLocal With Java Virtual Threads: Memory Costs, Inheritance and Alternatives
ThreadLocal works on virtual threads, but per-thread caches stop paying off when every task gets a new thread. A measured comparison, InheritableThreadLocal copying and how to turn it off, finding thread-local use with jdk.traceVirtualThreadLocals, and what to use instead.
kvi5hnuCode Sprout team member7 min readOn this page
ThreadLocal gives each thread its own copy of a variable. For two decades, Java code has used it for two things: caching objects that are expensive or not thread-safe, and passing context, such as the current user, a transaction or a request ID, without adding a parameter to every method.
Virtual threads support ThreadLocal fully: each virtual thread has its own values, and they are separate from the carrier's (article 11). Nothing breaks. But both uses rest on an assumption that virtual threads remove: that there are a few threads that live a long time. With one virtual thread per task, threads are many and short-lived, and thread-locals start to cost more than they save.
Caches stop working
A classic pattern caches one instance per thread of something that isn't thread-safe, such as SimpleDateFormat, a MessageDigest or a large scratch buffer. With a pool of 8 threads, the application creates 8 instances and reuses them for millions of tasks.
With a virtual thread per task, every task runs on a new thread, whose thread-local is empty. So every task creates its own instance, uses it once and throws it away. The "cache" now costs an allocation per task and holds one instance per concurrent task, which can be tens of thousands.

Measuring it
The program below runs 10,000 tasks that each use a 64 KiB scratch buffer from a ThreadLocal, first on a pool and then with a virtual thread per task. It then shows two more effects: inheritance into child threads, and a value left behind on a pooled thread:
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
/** Pretend this buffer is expensive to create and not thread-safe, so each thread caches its own. */
static final AtomicInteger buffersCreated = new AtomicInteger();
static final ThreadLocal<byte[]> SCRATCH = ThreadLocal.withInitial(() -> {
buffersCreated.incrementAndGet();
return new byte[64 * 1024]; // 64 KiB per thread
});
static void handle(int request) {
byte[] buffer = SCRATCH.get(); // reuse this thread's buffer
buffer[request % buffer.length] = 1;
}
static int run(ExecutorService executor, int requests) {
buffersCreated.set(0);
try (executor) {
for (int i = 0; i < requests; i++) {
int r = i;
executor.submit(() -> handle(r));
}
}
return buffersCreated.get();
}
static final InheritableThreadLocal<String> TENANT = new InheritableThreadLocal<>();
public static void main(String[] args) throws Exception {
// 1. A per-thread cache works with a pool and is useless with a thread per task
int pooled = run(Executors.newFixedThreadPool(8), 10_000);
int virtual = run(Executors.newVirtualThreadPerTaskExecutor(), 10_000);
System.out.println("10,000 requests, fixed pool of 8: buffers created = " + pooled);
System.out.println("10,000 requests, virtual per task: buffers created = " + virtual
+ " (" + virtual * 64 / 1024 + " MiB allocated)");
// 2. Inheritable thread-locals are copied into every virtual thread started from this one
TENANT.set("acme");
String[] seen = new String[2];
Thread inherits = Thread.ofVirtual().start(() -> seen[0] = TENANT.get());
Thread isolated = Thread.ofVirtual().inheritInheritableThreadLocals(false)
.start(() -> seen[1] = TENANT.get());
inherits.join();
isolated.join();
System.out.println("child inherits tenant: " + seen[0] + "; with inheritance off: " + seen[1]);
// 3. A value left behind leaks into later work on a pooled thread (but not on a fresh one)
ThreadLocal<String> user = new ThreadLocal<>();
try (ExecutorService one = Executors.newSingleThreadExecutor()) {
one.submit(() -> user.set("alice")); // forgot user.remove()
System.out.println("next task on the pooled thread sees user: " + one.submit(user::get).get());
}
try (ExecutorService fresh = Executors.newVirtualThreadPerTaskExecutor()) {
fresh.submit(() -> user.set("alice"));
System.out.println("next task on a new virtual thread sees user: " + fresh.submit(user::get).get());
}
// Thread-safe, immutable objects need no thread-local at all
DateTimeFormatter iso = DateTimeFormatter.ISO_LOCAL_DATE;
System.out.println("shared formatter: " + iso.format(java.time.LocalDate.of(2026, 11, 18)));
}
}
Output:
10,000 requests, fixed pool of 8: buffers created = 8
10,000 requests, virtual per task: buffers created = 10000 (625 MiB allocated)
child inherits tenant: acme; with inheritance off: null
next task on the pooled thread sees user: alice
next task on a new virtual thread sees user: null
shared formatter: 2026-11-18
- The cache is defeated. Eight buffers served 10,000 tasks on the pool. With virtual threads, the same code allocated 10,000 buffers, 625 MiB of garbage in total. If those tasks had been waiting at the same time, as they do in a busy server, all of that memory would have been live at once.
- Inheritance copies values. An
InheritableThreadLocalis copied into each thread started from the current one, virtual threads included. That's often what you want for context, but each copy costs something, and with many threads it adds up.Thread.Builder.inheritInheritableThreadLocals(false)turns it off for threads created by that builder. - Leftover values leak on pools, not on fresh threads. A pooled thread kept "alice" for the next task, which is a classic security bug when code forgets
remove(). A new virtual thread starts empty. This is one way virtual threads make code safer.
Context: still works, with costs
Passing context through thread-locals, such as a security principal, a logging MDC or a transaction, still works on virtual threads. Frameworks such as Spring Security, SLF4J's MDC and JTA transaction managers keep working. The costs to watch:
- Memory. Each live virtual thread holds its own copy. Keep context values small: IDs, not whole object graphs.
- Inheritance. A request thread that fans out to 20 child threads copies its inheritable values 20 times. Values that are mutable objects are shared by reference after the copy, so a child changing one can affect the parent.
- No clear lifetime.
sethas no matching end. A value lives untilremove()or until the thread ends. With virtual threads, the thread usually ends with the task, which helps, but the code doesn't show where the value is valid.
Scoped values (java.lang.ScopedValue, final since Java 25) were designed for exactly this: immutable context with a clear, lexical lifetime, cheap inheritance into structured child tasks, and no remove() to forget. Part 5 covers them in depth. A short preview:
public class ScopedPreview {
static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(REQUEST_ID, "req-42").run(() -> log("loading traveler"));
System.out.println("bound outside the scope? " + REQUEST_ID.isBound());
}
static void log(String message) {
System.out.println("[" + REQUEST_ID.get() + "] " + message); // no parameter needed
}
}
Replacing thread-local caches
When a thread-local was a cache, choose a replacement by the reason it existed:
| Why it was cached | Replacement |
|---|---|
| The object isn't thread-safe, but a thread-safe version exists | share one instance: DateTimeFormatter instead of SimpleDateFormat, ThreadLocalRandom or a shared RandomGenerator where appropriate |
| The object is cheap to create | create it where it's needed and let the GC handle it. Young-generation allocation is very cheap |
| The object is genuinely expensive (large buffers, parsers, cipher instances) | a small, bounded object pool, or a buffer passed down as a parameter |
| It held a connection or session | a proper connection pool (HikariCP, the HTTP client's own pool) |
ThreadLocalRandom is a special case worth knowing: it doesn't allocate a separate object per thread. It stores its state in fields of the Thread object itself, so it's fine on virtual threads.
Finding thread-local use
Before switching a large application to virtual threads, find out which libraries use thread-locals. Start the JVM with:
java -Djdk.traceVirtualThreadLocals MyApp
The JVM then prints a stack trace whenever code running on a virtual thread sets a thread-local value (including the first get() of a withInitial thread-local). It prints a trace every time, so expect repeats for hot call sites. In the program above, it pointed straight at Solution.handle. Third-party libraries show up the same way, telling you which dependencies to upgrade or configure. Memory profilers and heap dumps (looking for many ThreadLocalMap entries) complete the picture.
What's current
ThreadLocalandInheritableThreadLocalare fully supported on virtual threads, andThread.Builder.inheritInheritableThreadLocals(false)controls copying.- An early preview option that let builders forbid thread-locals entirely was dropped before virtual threads became final in Java 21.
ScopedValueis final in Java 25 (JEP 506). It's the recommended way to share immutable context with virtual threads and structured concurrency.- Libraries have been adapting. For example, Jackson 2.16 added pluggable buffer-recycler pools as an alternative to its thread-local buffers, with virtual threads as the motivation. Check your dependencies' release notes, as upgrading often removes the problem.
Common questions
Do I have to remove all ThreadLocals before using virtual threads?
No. They work correctly. Look at the ones that cache large objects or hold large context, because those cost memory per thread. Small context values such as IDs are fine.
Can a virtual thread see its carrier's thread-locals? No. A virtual thread has its own thread-locals, and those of its carrier are invisible to it. The JDK has an internal "carrier thread-local" for its own use, but there's no public API for it.
Does setting a thread-local on a virtual thread pin it?
No. Thread-locals are ordinary fields of the Thread object, so they have nothing to do with mounting.
Why does remove() matter less with virtual threads?
Because each task usually gets a fresh thread, a value can't leak into the next task. It still matters when a long-running virtual thread processes many items in a loop.
Summary
ThreadLocalworks on virtual threads, and each virtual thread has its own values.- Per-thread caches stop working with one thread per task: each task allocates its own copy, and memory grows with concurrency.
InheritableThreadLocalvalues are copied into child threads. Disable that withinheritInheritableThreadLocals(false)when it isn't needed.- Fresh virtual threads start empty, which removes the classic leftover-value leaks of pooled threads.
- Replace caches with shared thread-safe objects, plain allocation or bounded pools, and use
ScopedValuefor context. -Djdk.traceVirtualThreadLocalsfinds the code that sets thread-locals on virtual threads.
Practice questions
A service caches a 1 MiB parser per thread in a ThreadLocal. After moving to virtual threads, it handles 5,000 concurrent requests. Roughly how much memory do the parsers use, compared with a 200-thread pool?
Answer
About 5 GB (5,000 × 1 MiB) while all requests are in progress, plus a constant stream of new parsers, compared with about 200 MiB (200 × 1 MiB) on the pool. Replace the thread-local with a bounded pool of parsers, or a thread-safe parser if one exists.
What does this print?
InheritableThreadLocal<String> tl = new InheritableThreadLocal<>();
tl.set("parent");
Thread t = Thread.ofVirtual().start(() -> tl.set("child"));
t.join();
System.out.println(tl.get());
Answer
parent. The child gets its own copy of the value at start. Setting it in the child changes only the child's copy. (If the value were a mutable object and the child modified it instead of replacing it, the parent would see the change, because both copies refer to the same object.)
Why is a shared DateTimeFormatter a better choice than a thread-local SimpleDateFormat on virtual threads?
Answer
DateTimeFormatter is immutable and thread-safe, so one instance can serve every thread. A thread-local SimpleDateFormat would be created again on every new virtual thread, which means once per task.
Previous: Java Virtual Threads and Native Code: FFM Calls, File I/O and Other Limitations
Next: Monitoring Java Virtual Threads With JFR: Pinning, Lifecycle and Submit-Failed Events

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.