Scrivio Interview library
DebuggingIntermediate8 min read · updated 12 November 2026

A Spring Boot service moved to virtual threads, and memory use rose sharply; heap dumps show millions of ThreadLocal values holding buffers and date formatters. In another service, user ids from one request appear in another request's logs. Explain both problems.

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.

Java
// Written for a pool of 200 platform threads
private static final ThreadLocal<byte[]> BUFFER =
ThreadLocal.withInitial(() -> new byte[64 * 1024]); // one per thread
private static final ThreadLocal<SimpleDateFormat> FORMAT =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));
// 200 platform threads -> 200 buffers, about 12.5 MB, each reused thousands of times
// 100,000 virtual threads -> 100,000 buffers, about 6.1 GB, each used once

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.

Java
private static final DateTimeFormatter FORMAT = DateTimeFormatter.ISO_LOCAL_DATE_TIME; // shared, safe
// Small buffers: just allocate
byte[] buf = new byte[8 * 1024];
// Large buffers: a bounded pool, independent of the thread count
private final BlockingQueue<ByteBuffer> pool = new ArrayBlockingQueue<>(256);
ByteBuffer borrow() { ByteBuffer b = pool.poll(); return b != null ? b.clear() : ByteBuffer.allocate(64 * 1024); }
void giveBack(ByteBuffer b) { pool.offer(b); } // extra buffers are simply dropped

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.

Java
public class UserMdcFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
MDC.put("userId", currentUser(req)); // set for this request
chain.doFilter(req, res);
// never removed: the next request on this thread starts with the old userId
}
}
Step throughStale MDC on a pooled thread
Request APool thread 7Request B
MDC.put(userId, 42)
log: userId=42, correct
request ends, MDC not cleared
anonymous request arrives
log: userId=42, wrong user

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.

Java
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
try (MDC.MDCCloseable c = MDC.putCloseable("userId", currentUser(req))) {
chain.doFilter(req, res);
} // removed here, even on an exception
}
// For a plain ThreadLocal
CONTEXT.set(ctx);
try { handle(); } finally { CONTEXT.remove(); }

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.

Java
static final ScopedValue<String> USER = ScopedValue.newInstance();
void handle(Request r) {
ScopedValue.where(USER, r.userId()).run(() -> service.process(r));
}
// deep in the call stack
String who = USER.get(); // "42" inside the scope
// after run() returns, USER is unbound on this thread: USER.isBound() == false

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.

What to say in the interviewAbout 90 seconds aloud

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/