Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

A service sets a large per-request object into a ThreadLocal in an interceptor, and memory slowly grows even though requests are short. A heap dump shows those objects referenced from Thread objects of the request pool. What is wrong?

Request threads in a pool live as long as the application, and a value stored in a ThreadLocal stays reachable from its thread until it is removed or overwritten. The interceptor sets a large object but does not always clear it, for example when an exception skips the cleanup, so every pool thread ends up holding one, and the heap dump path Thread -> threadLocals -> entry -> value shows exactly that. The fix is to remove the value in a finally block or in the interceptor's afterCompletion callback, and better still not to keep large objects in ThreadLocals at all but to pass them explicitly.

Why this question is asked

ThreadLocal is a convenient way to carry request context, a tenant, a user or a trace id, through code that does not take it as a parameter, and Spring itself uses it for transactions and security. That convenience makes it easy to forget that pool threads never end, so anything we put there lives far longer than the request. Interviewers ask this because it combines three skills: knowing how ThreadLocal stores its values, knowing the Spring MVC request lifecycle, and reading a heap dump. In this answer, we will recap how ThreadLocal works, see why pool threads keep the values, find the code paths that skip cleanup, fix them, and confirm the leak path in a heap dump.

1A Quick Recap: Where a ThreadLocal Value Is Stored

A ThreadLocal gives each thread its own copy of a variable. The surprising part is where that copy lives. It is not inside the ThreadLocal object. Each Thread object has a field called threadLocals, which holds a ThreadLocalMap, a small hash table. When we call ctx.set(value), Java finds the current thread's map and stores an entry with our ThreadLocal as the key and our object as the value.

The key is held through a weak reference, which means the garbage collector may clear it if nothing else references the ThreadLocal. The value is held strongly. So as long as the thread is alive and the entry has not been removed, the value cannot be collected.

Step throughThe reference chain that keeps the value alive
  1. Thread (http-nio-8080-exec-17)a GC root while it runs; pool threads never end
  2. threadLocals: ThreadLocalMapone per thread
  3. Entry[] tableone entry per ThreadLocal used by this thread
  4. Entry: weak key -> RequestContextthe value is a strong reference
  5. RequestContext, 4 MBparsed payload, report data, caches ...

5 layers, from the top down. Step through them one at a time.

2Why Pool Threads Keep the Values

In a simple program where each task gets a new thread, ThreadLocal values die with the thread. A web server works differently. Tomcat creates up to 200 request threads (its default maximum) and reuses them for the life of the application, which may be weeks. A value set on thread exec-17 during request 1 is still there when request 2, 3 and 4,000 run on the same thread, unless someone removed it.

This explains the slow growth. At startup only a few threads have been used. As traffic rises, Tomcat creates more threads, and each one that runs our interceptor ends up with its own large object attached. With a 4 MB object and 200 threads, that is up to 800 MB held by threads that are mostly idle. If the object accumulates data, for example a list that the code appends to on each request instead of replacing, it grows without limit. A value may also be overwritten by the next request, which hides the problem in testing, but any thread whose last request skipped the cleanup keeps its old value indefinitely.

3The Code Paths That Skip Cleanup

Here is the kind of interceptor that causes this. It sets the context in preHandle and clears it in postHandle.

Java
public class ContextInterceptor implements HandlerInterceptor {
static final ThreadLocal<RequestContext> CTX = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
CTX.set(RequestContext.load(req)); // about 4 MB for large tenants
return true;
}
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView mv) {
CTX.remove(); // never runs if the controller throws
}
}
Which Spring MVC callbacks run
SituationpostHandleafterCompletion
Controller returns normallyrunsruns
Controller throws an exceptionskippedruns, with the exception
This interceptor's preHandle returned true, a later one falseskippedruns
This interceptor's preHandle returned falseskippedskipped

The bug is in the choice of callback. Spring MVC calls postHandle only when the handler completes normally. If the controller throws an exception, postHandle is skipped, and the value stays on the thread. The same happens if a later interceptor's preHandle returns false, or if the code removes the value only at the end of a try block without a finally. Asynchronous requests are another path: the request is handed to another thread, and the original thread's callbacks differ.

4The Fix: Always Remove, and Prefer Not to Store Large Objects

The minimal fix is to move the cleanup to afterCompletion, which Spring calls after the response for every interceptor whose preHandle returned true, whether or not the handler threw. Even more robust is a servlet filter, where a plain try and finally guarantees the removal on every path.

Java
// Option 1: interceptor, clean up in afterCompletion
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
CTX.remove(); // runs on success and on exceptions
}
// Option 2: filter, cleanup guaranteed by finally
public class ContextFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
CTX.set(RequestContext.load(req));
try {
chain.doFilter(req, res);
} finally {
CTX.remove(); // always
}
}
}

Notice that we call remove(), not set(null). set(null) leaves an entry with a null value in the map; remove() deletes the entry. Both release the large object, but remove() keeps the map clean.

The better design question is why a 4 MB object needs to be in a ThreadLocal at all. ThreadLocals suit small context such as a tenant id or a trace id. A large payload is data our code works on, and it is clearer and safer to pass it as a parameter, or to keep it in a request-scoped bean that Spring discards at the end of the request. It also matters for the future: with virtual threads there can be thousands of threads, and Java 25's ScopedValue, now final, offers a way to share context for a bounded scope that is released automatically when the scope ends.

5Confirming the Leak Path in the Heap Dump

To prove the diagnosis, we take a heap dump with jcmd <pid> GC.heap_dump /tmp/heap.hprof and open it in Eclipse Memory Analyzer (MAT) or a similar tool. In the dominator tree, which ranks objects by how much memory they keep alive, we see many RequestContext instances. For one of them we ask for the path to GC roots, excluding weak references. The path reads: a Thread named http-nio-8080-exec-17, its threadLocals field, a ThreadLocalMap, its table array, an Entry, and the entry's value field pointing at our RequestContext.

Seeing Thread at the root, threadLocals in the middle and our class at the end confirms that nothing in our application references these objects any more; only the threads do. After the fix, a new heap dump under the same load shows few or no RequestContext instances between requests, and the old-generation usage stays flat.

6Follow-up questions

Does the weak reference to the key not prevent this leak?

No. The weak reference is on the ThreadLocal key, and our ThreadLocal is a static final field, so it is never collected anyway. Even when a key is collected, the entry's value is still strongly referenced and is only cleaned up lazily when the map happens to be used again. The weak key protects against leaking the ThreadLocal object itself, not against leaking the values.

Why does the problem not show in unit or integration tests?

Tests usually run few requests, on fresh threads, and mostly on the success path, so postHandle runs and clears the value. The leak needs many pool threads, a long-lived JVM and some failing requests. A test can catch it by sending a request that throws and then asserting that the ThreadLocal is empty on that thread, or by checking that the context is null at the start of each request.

How does this interact with @Async or thread pools inside the request?

A ThreadLocal set on the request thread is not visible on an executor thread, so code that relies on it may see null there. Teams often copy the context into the task with a TaskDecorator, and then the same rule applies on the executor thread: the decorator must clear it in a finally block, or the executor's threads collect stale contexts as well.

7Conclusion

In this answer, we saw that a ThreadLocal value lives in the thread's own ThreadLocalMap and stays reachable while the thread lives, which for a request pool means the life of the application. The interceptor cleared the value in postHandle, which Spring skips when the controller throws, so threads kept 4 MB objects and memory grew as more threads were used. We fixed it with afterCompletion or a filter with try and finally, argued for passing large objects explicitly instead, and confirmed the Thread -> threadLocals -> value path in a heap dump.

What to say in the interviewAbout 90 seconds aloud

Open with

The objects are leaking through the request threads. A ThreadLocal value is stored in the current thread's ThreadLocalMap, keyed weakly by the ThreadLocal but with a strong reference to the value, so it stays alive as long as the thread lives or until someone calls remove.

Then, if they want more

Tomcat's request threads live as long as the application, up to 200 of them, so any value that is not removed stays attached. Memory grows slowly because more threads get used as traffic rises, and each one ends up holding its own large object, or a growing one.

The usual reason the cleanup is skipped is that it is in postHandle, or at the end of a try without finally, and Spring does not call postHandle when the controller throws.

I would move the removal into afterCompletion, which runs even on exceptions, or use a servlet filter with set before chain.doFilter and remove in a finally block, and I would call remove rather than set null.

I would also question storing a large object in a ThreadLocal at all; it is better passed explicitly or held in a request-scoped bean, and ThreadLocals should hold small context like a tenant or trace id.

To confirm, I would take a heap dump and look at the path to GC roots for one of the objects: Thread, threadLocals, the map's table, an Entry, and its value.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
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.
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 service sets a large per-request object into a ThreadLocal in an interceptor, and...": https://scrivio-interview-library.netlify.app/java/concurrency-problems/7b769dab18/