Quick revision
The short answer
Both problems come from ThreadLocal assumptions that no longer hold. The first service cached buffers and formatters in ThreadLocal on the assumption of a small pool of long-lived threads; with virtual threads there is one thread per request, possibly millions, so the caches multiply memory and are rarely reused. The second service sets ThreadLocal or MDC values for each request on pooled threads and never clears them, so the next request on that thread inherits the old user id. The fixes are thread-safe shared objects or explicit pools for the first, clearing context in a finally block or a filter for the second, and ScopedValue for new per-request context.
What to remember
In this answer, we saw two failures of the same tool. ThreadLocal caches assumed a small, reused pool of platform threads; with virtual threads, every request gets a fresh thread, so the caches multiply memory and give no reuse, and we fix it with thread-safe shared objects such as DateTimeFormatter or with explicit bounded pools. ThreadLocal and MDC context that is not cleared stays on pooled threads, so the next request logs or even acts as the previous user, and we fix it by clearing in finally or a filter. ScopedValue gives new code bounded, immutable context that cannot leak, and concurrent tests catch both problems before production does.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Both problems come from ThreadLocal assumptions that no longer hold. The first service cached buffers and formatters in ThreadLocal on the assumption of a small pool of long-lived threads; with virtual threads there is one thread per request, possibly millions, so the caches multiply memory and are rarely reused. The second service sets ThreadLocal or MDC values for each request on pooled threads and never clears them, so the next request on that thread inherits the old user id. The fixes are thread-safe shared objects or explicit pools for the first, clearing context in a finally block or a filter for the second, and ScopedValue for new per-request context.
Why this question is asked
ThreadLocal has been a quiet workhorse in Java servers for twenty years, used both as a cache and as a way to carry request context. Its behaviour depends entirely on how threads are created and reused, so a change in threading model, like turning on virtual threads in Spring Boot, can change memory use and correctness overnight. Interviewers like this pair of symptoms because they are opposite failure modes of the same tool. In this answer, we will recap how ThreadLocal stores values, explain why virtual threads multiplied memory, explain how user ids leak between requests, fix both, look at ScopedValue as the modern alternative, and finish with how to test for these problems.
1A Quick Recap of How ThreadLocal Stores Values
A ThreadLocal is a key, and each Thread object holds a small map from those keys to values. When code calls tl.get(), it looks up the value in the current thread's map. So a value lives exactly as long as the thread lives, or until someone calls remove().
That design was built around platform threads, which are expensive operating system threads. Servers kept a fixed pool of perhaps 200 of them, and each thread served thousands of requests in turn. So a ThreadLocal cache built 200 objects and reused each one thousands of times, and a ThreadLocal context value stayed on the thread after the request unless it was cleared.
2Problem 1: Why Virtual Threads Multiplied the Memory
With spring.threads.virtual.enabled=true, Spring Boot 3.2 and later run each request on a new virtual thread. Virtual threads are cheap, a few hundred bytes to a few kilobytes each, so the JVM can have hundreds of thousands or millions of them alive. They are not pooled: a virtual thread runs one task and ends.
Now look at a typical ThreadLocal cache. Every new virtual thread finds its map empty, so it creates its own 64 KB buffer and its own SimpleDateFormat, uses them for one request and holds them until the thread ends. If 100,000 requests are in flight, because many are waiting on I/O, that is 100,000 buffers, about 6 GB, instead of 200. And the cache gives no benefit, because nothing is ever reused.
So the caching idea assumed a small, pooled set of threads. That assumption silently broke when the threading model changed.
3Fix 1: Share Thread-Safe Objects or Use an Explicit Pool
For formatters, the answer is to stop caching per thread. DateTimeFormatter is immutable and thread-safe, so one static constant serves every thread. For buffers, either allocate per request when they are small, since allocation in the young generation is very cheap, or use an explicit bounded pool when they are large, so the memory is capped no matter how many threads exist.
Notice that the pool's size is set by us, 256 buffers, not by the number of threads. Libraries can be the culprit too; heap dumps grouped by the ThreadLocal's owning class usually show which library still caches per thread, and many have released versions that check for virtual threads (check your versions).
4Problem 2: How User Ids Leak Between Requests
The second service is probably still on platform threads, or uses a pool somewhere, for example an @Async executor. A filter or interceptor puts the user id into a ThreadLocal, or into SLF4J's MDC, which is itself built on ThreadLocal, so every log line shows it. If the code never clears it, the value stays on the pool thread after the request ends.
5 messages in order. Play them, or step through them one at a time.
The value outlives the request because the thread outlives the request.
Now picture a request without a logged-in user, or a code path that only sets the id when it is present. It runs on a thread that last served user 42, and its log lines say userId=42. Worse, if the same ThreadLocal feeds authorisation decisions, one user can act with another user's identity. The same happens when chain.doFilter throws, because the code after it never runs.
5Fix 2: Always Clear Context in finally
The rule is that whoever sets context must clear it, in a finally block, so that it is cleared even when the request fails. Using MDC.putCloseable with try-with-resources is a tidy way to write it.
Work handed to another executor needs its context copied in and cleared out at the boundary as well, for example with a Spring TaskDecorator. Otherwise the pool threads accumulate stale values of their own.
6ScopedValue: Context That Cannot Leak
Java now has ScopedValue, finalised in Java 25 after several previews (check your version). A scoped value is bound for the duration of one call and is unbound automatically when that call returns, whether normally or with an exception. It is immutable inside the scope and is inherited by child tasks forked in a StructuredTaskScope. So there is nothing to clear and nothing to leak.
Scoped values are also cheap with millions of virtual threads, because they are not a per-thread map that grows and lingers. For logging, MDC still needs ThreadLocal today, so we clear it reliably; for our own context, ScopedValue is the better default in new code.
7Testing for Both Problems
Both bugs are invisible with one request at a time, so tests must run requests concurrently. For leaks, a test fires a few hundred requests for different users, plus some anonymous ones, through a small thread pool, and asserts that each response and each captured log line carries its own user and that the context is empty after each request. For memory, a load test with realistic concurrency on virtual threads, followed by a heap histogram (jcmd <pid> GC.class_histogram) or a heap dump, shows whether per-thread objects grow with the number of requests in flight.
8Follow-up questions
Why not keep ThreadLocal caches and just limit the number of virtual threads?
Because that throws away the point of virtual threads, which is cheap concurrency for blocking work. It is better to fix the caching so memory no longer depends on the thread count, using a shared thread-safe object or a bounded pool.
Does InheritableThreadLocal help with executors?
No, it makes things worse. It copies values only when a thread is created, so pooled threads keep whatever values they inherited at creation, which is usually not the current request's context. Explicit capture and restore at the executor boundary, or ScopedValue with structured concurrency, is the correct approach.
Do virtual threads support ThreadLocal at all?
Yes, they support ThreadLocal fully, so existing code keeps working. The problem is cost and assumptions, not correctness: each virtual thread has its own copy, so per-thread caching no longer saves anything.
How did you find the offending ThreadLocals in the heap dump?
In a tool such as Eclipse MAT, I would look at the dominator tree for byte arrays and SimpleDateFormat instances, then follow their paths to GC roots, which go through Thread objects and their ThreadLocalMap entries. The ThreadLocal's referent class points to the code or library that created it.
9Conclusion
In this answer, we saw two failures of the same tool. ThreadLocal caches assumed a small, reused pool of platform threads; with virtual threads, every request gets a fresh thread, so the caches multiply memory and give no reuse, and we fix it with thread-safe shared objects such as DateTimeFormatter or with explicit bounded pools. ThreadLocal and MDC context that is not cleared stays on pooled threads, so the next request logs or even acts as the previous user, and we fix it by clearing in finally or a filter. ScopedValue gives new code bounded, immutable context that cannot leak, and concurrent tests catch both problems before production does.
Open with
These are two sides of the same ThreadLocal assumption. In the first service, code cached buffers and SimpleDateFormat instances in ThreadLocal. That made sense with a pool of a couple of hundred platform threads, where each cached object was reused thousands of times.
Then, if they want more
With virtual threads, Spring runs every request on a new thread, and there can be hundreds of thousands at once, so every thread builds its own buffer and formatter, uses them once and holds them until it ends. Memory now grows with the number of requests in flight.
I would replace the formatter with a static DateTimeFormatter, which is immutable and thread-safe, and either allocate small buffers per request or use a bounded pool for large ones, so memory no longer depends on the thread count.
In the second service, a filter puts the user id into ThreadLocal or MDC and never clears it, so on pooled threads the next request, for example an anonymous one, inherits the previous user's id, and it also happens when the request throws.
The fix is to always clear in finally, or with MDC.putCloseable in try-with-resources, and to copy and clear context at executor boundaries. For new code I would use ScopedValue, final in Java 25, which is bound only for the duration of a call and cannot leak.
And I would add concurrent tests that check every request sees only its own context.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 25, Spring Boot 3.2
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- JLS chapter 17, Threads and Locks
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A Spring Boot service moved to virtual threads, and memory use rose sharply; heap dumps...": https://scrivio-interview-library.netlify.app/java/java-memory-model/79b89d358a/