Lesson · Virtual Threads & Structured Concurrency
ThreadLocal on virtual threads: the cost moves
15 min readVirtual Threads & ThreadLocal
Virtual threads make threads cheap, and that flips the arithmetic of per-thread state. A ThreadLocal entry is a small object stored on every live thread that sets it, so the bill is threads times keys times a constant: invisible across a thousand pooled workers, material across a hundred thousand virtual threads. This lesson is about that arithmetic, about the reuse problem that survives in the pooled parts of the system, and about the order of the fixes: explicit parameters first, a bounded scope next.
Thread-per-request came back, with the context pack attached
For twenty years the advice was to avoid one thread per request, because operating system threads are expensive and a pool amortises them. Virtual threads remove that reason: they are cheap enough to start one per task, and the code can go back to the simple shape of read, handle, respond (the creating-virtual-threads lesson covers the factories).
The context is the part worth staring at. Most request paths carry ambient state that no method declares: the logging MDC, the security principal, the transaction in flight, a tenant id, a trace id. All of it lives on the thread, and libraries three layers down read it without being handed anything.
The ThreadLocal lesson covers how that storage works and why remove() belongs in a finally. This lesson answers the question that only appears at virtual-thread scale: what happens to the plan when the number of live threads stops being bounded by the CPU count?
Threads became cheap; the state they carry did not.
What one set ThreadLocal costs, per thread
The map is a field on Thread. Each thread owns its ThreadLocalMap, and each ThreadLocal that has been set in that thread adds one entry: a weak reference to the key, a strong reference to the value. A thread that has never touched a ThreadLocal carries nothing at all; a thread that has set three of them carries a table with three entries and the objects behind them.
The order of magnitude for a small map is a few hundred bytes per thread: the map object, its table, and one entry per key, plus the value graph the entries hold strongly. The lab in this lesson uses an authored estimate of that shape rather than a measurement, because the constant is not the point. The point is the multiplier.
| Part | Lives where | Paid |
|---|---|---|
| The ThreadLocal object | one per declaration, shared by every thread | once |
| The ThreadLocalMap | a field on each Thread | per thread that has set something |
| An entry per key | inside that thread's map | per thread per ThreadLocal set in it |
| The value graph | the heap, held strongly by the entry | per thread, for as long as the entry lives |
The map is a field on the thread, so the bill arrives once per thread that has ever set a value.
The multiplier: live threads times per-thread state
Run the numbers on one context key: a thousand pooled workers with a small map each stay in the low megabytes and never show up in a heap graph. A hundred thousand virtual threads in flight at once pay the same cost a hundred thousand times, for a context record most requests read once, near the top of the call chain.
Add the real key count. A codebase with an MDC, a security context and a transaction binding has three keys before anyone writes a new one, and the value each entry holds strongly can be much larger than the entry: a request object, a session map, a transaction with its own graph.
Three numbers decide the bill, and all three are visible in the design: the live-thread count, the number of bound keys, and the size of what each key points at. Virtual threads move the first number, not the second or the third.
Per-thread state scales with the deployment, not with the work: the same context read once still costs once per live thread.
Virtual-thread context lab
authored numbers: a shape, not a benchmarkdeployment
the same workers handle request after request
context storage
retained across live threads
scale: 293 MB = 1M threadsOne small map per live thread per key. The constant is an authored estimate; the multiplier is live threads times keys, and it is the part virtual threads move.
the same day, step by step
request 1 lands on worker-2 and sets CURRENT to alice.
request 1 ends; nothing ran remove() on the way out.
worker-2 is not retired between tasks: it goes back to the queue with the entry still in its map.
request 2 lands on worker-2, calls get(), and is told alice.
verdict
reused workers keep what you forget
A thousand workers holding a small map each is invisible in any heap graph, so the size is not the lesson here. Reuse is: request 2 can read request 1's user, and nothing in the call that reads it says so. A remove() in a finally, on the same thread that set the value, is the whole fix.
The old leak is gone; the pooled parts are not
State the good news plainly, because it changes the guidance: virtual threads are not pooled, and a terminating thread takes its map with it. A forgotten remove() on a per-task virtual thread does not hand a value to the next request, because there is no next request on that thread. The classic wrong-user bug is rare on a pure per-task path.
Real services are not pure. They keep fixed pools for CPU-bound work, scheduled jobs and libraries that create their own executors. The moment a task runs on a reused thread, the old rules return in full: the value set by one task is still in the map for the next one, and the code that reads it cannot tell.
A quieter lifetime problem survives even on virtual threads. The entry holds the value strongly for as long as the thread lives, so on a long-running task a context that stopped being true is still reachable from the thread and still keeps its object graph alive.
- Request 1 runs on worker-2, sets CURRENT to alice, and returns to the pool without a remove().
- Worker-2 keeps the entry: alice is reachable from a live thread that has no idea it is there.
- Request 2 lands on worker-2 and calls get(): the map answers, so an audit line names alice.
- remove() in a finally, on the same thread that set the value, prevents both the retention and the misattribution.
On per-task virtual threads a forgotten cleanup is a footprint problem; on anything reused it is the old bug, unchanged.
InheritableThreadLocal: inheritance by copy, at thread creation
InheritableThreadLocal copies the parent's inheritable values into the child at thread creation. With virtual threads created per task, the creating thread is usually the submitter, so the child often inherits what the submitting code held, and the design looks like it works.
Look at the mechanism and the problem is visible. Inheritance is a copy of the whole map, taken at an instant that has nothing to do with the request, and it grows with every key the parent has accumulated. With a pooled executor the thread was created long before the task existed, so the snapshot belongs to the wrong moment entirely, which the ThreadLocal lesson works through.
Scoped values inherit differently: a child started inside the bound scope reads the same binding by reference, and the scope bounds how long that can remain true. That is the next lesson. The takeaway here is narrow and useful: inheritance by copy is a cost and a timing hazard, not a foundation for request context.
| Mechanism | When a child sees the value | Cost | What breaks |
|---|---|---|---|
| ThreadLocal | never: it must be handed over or set again | none | every call site needs the value or needs to set it |
| InheritableThreadLocal | at thread creation, by copying the parent's map | a copy of the parent's entries per child | pools create threads before tasks; copies grow with the key count |
| ScopedValue | child threads started inside the bound period | a pointer, no copy | nothing outside the scope sees it, and children must finish inside it |
Inheritance by copy happens at a moment you do not control; inheritance by reference is bounded by a scope you do.
Where the context lives · two scaling laws
per live thread, or per scope
ThreadLocal · a map per live thread
cost × threadsEach thread that has set a value holds a small table with one entry per key, plus a strong reference to the value. Authorship estimate: a few hundred bytes per thread; multiply by live threads and by keys.
ScopedValue · one binding per scope
cost × scopeswhere(CURRENT, ctx).run( ... )
binding · CURRENT = ctx
created once, for this block
A child thread inherits a pointer, not a copy, and the block bounds how long anyone can read it. When run returns, the binding is restored and nothing was stored on any thread.
The difference is the multiplier. Per-thread maps grow with the number of threads that are alive at once; a binding is created once for a scope and shared by everything inside it.
What to reach for instead
The options, in order of preference, run from the most explicit to the most careful:
- List every ThreadLocal set on a request path today: MDC, security, transaction, tenancy, plus anything your own code added.
- Multiply: keys times live threads times the per-thread constant. That is the ambient bill at your concurrency target.
- For each key, ask whether the flow is one-way and the value immutable. One-way and immutable is a scoped-value candidate.
- For each set(), find the finally that removes it on the same thread. Any path that can skip it is a bug waiting for a reused thread.
- Prefer a parameter where the call chain is short; reach for a scope where the context is genuinely framework-shaped.
- Pass it explicitly when the call chain can take a parameter. It costs one signature per layer and the compiler keeps every caller honest, which is exactly what ambient state does not do.
- Use a scoped value for genuine one-way ambient context: read-only, bounded to a block, inherited by structured children, with nothing to remove. The next lesson builds it out.
- Keep legacy ThreadLocals hygienic where a library forces them: set close to the leaf, remove in a finally, keep the stored graph small, and count each key as part of the per-thread bill.
- Prefer framework support where it exists: logging, security and tracing libraries are moving their own context off long-lived thread state, and an upgrade is often cheaper than a cleanup you maintain.
The migration is not all-or-nothing: parameters for new code, a scope for context, hygiene for what remains.
Remember
The semantics of ThreadLocal do not change on virtual threads. The arithmetic does.
- Per thread, per key: every set value is another entry on every live thread that carries it, plus the graph it holds strongly.
- Cost scales with live threads: a thousand workers hide the bill, a hundred thousand threads do not, and short-lived threads shrink the lifetime rather than the memory.
- Reuse is where the bug lives: per-task threads retire their maps, pooled workers keep them, and keep the previous task's user with them.
- Prefer parameters, then scoped values, then careful hygiene for keys you cannot move yet.
A ThreadLocal is a per-thread cost you pay per thread; a million threads is a million times the discipline.
Cheap threads, expensive habits
A service moves its request path to virtual threads and keeps the ThreadLocal context pack: MDC, principal, transaction. Latency improves, and every live request now carries a map table and a handful of entries for values that were read once. At ten thousand concurrent requests it is a rounding error; at a million it is hundreds of megabytes of scaffolding that no profiler line calls out by name. The old wrong-user bug does not appear on the per-task path, because each thread dies with its task, and that is what makes the footprint easy to miss: the code looks correct, and the cost hides inside the success.
Interview angles
Does ThreadLocal still work on virtual threads?+
Yes, with unchanged semantics: each thread owns its map, and get and set only ever see the calling thread's values. What changes is the arithmetic, because the same small per-thread cost now lands on many more live threads.
So is the classic pool leak gone once everything runs on virtual threads?+
Only on the parts that really start one thread per task. Virtual threads are not pooled and a terminating thread takes its map with it, so a forgotten remove() cannot hand a value to the next request. Any task running on a reused thread behaves exactly as before.
Keep remove() in a finally anyway: it bounds how long the value stays reachable on long-running tasks, and it keeps the code correct for the pooled paths that always remain somewhere in the system.
Common misconception: Moving to virtual threads makes ThreadLocal safe again.
What does a set ThreadLocal cost per thread, exactly?+
A map object, a table and one entry per ThreadLocal set in that thread, plus a strong reference to the value. Small in absolute terms, multiplied by live threads and by keys.
The strong reference is the part people underestimate: the entry can be tiny while the graph behind it, a session map or a transaction, is large, and it stays reachable while the thread lives.
Why is InheritableThreadLocal the wrong tool for request context, even when it seems to work?+
It copies the parent's entries at thread creation. With per-task virtual threads the creator is often the submitter, so it looks right; with any pool the snapshot is taken at the wrong moment, and the copy grows with every key.
How do scoped values change this picture?+
They are read-only, bounded to a block, and inherited by reference: a child started inside the scope reads the same value with no per-thread map and nothing to remove. That removes both the multiplier and the discipline.
It must be immutable, or every access to it must be synchronized. A scoped value shares one object with the child threads; it does not hand each thread a copy the way an inheritable ThreadLocal does.
Follow-up: What has to be true about the value itself before you share it across threads that way?
You inherit a virtual-thread service with five ThreadLocals on the request path. What do you do first?+
Count before you change anything: keys times live threads is the ambient bill. Then work down the list, parameters where the chain is short, a scope where the context is genuinely ambient, and a finally-remove for every key you cannot move yet.
Follow-up: Which of those five keys would you migrate first, and why?