Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

A servlet filter does BUFFER.set(new byte[1_000_000]) at the start of each request, where BUFFER is a static ThreadLocal<byte[]>, but never calls remove. What are the problems?

Because servlet container threads are pooled, the 1 MB array stays attached to each thread after the request ends, so every pool thread keeps 1 MB alive forever, and in a redeployed web application a stale value whose class comes from the application can keep the old class loader alive. If the ThreadLocal ever holds user data, the next request on that thread can see another user's data. The fix is to call remove() in a finally block, and better still to pass data explicitly or use scoped values, final in JDK 25.

Why this question is asked

ThreadLocal looks like a convenient way to give each request its own scratch space, and in many code bases it is used exactly like this. The trouble is that it is attached to the thread, not to the request, and in a server the thread outlives the request. Interviewers ask this question because the same mistake causes memory waste, class loader leaks and, in the worst case, one user seeing another user's data. In this answer, we will recap how ThreadLocal stores values, look at the broken filter, go through each problem it causes, and then fix it with remove() and with better designs.

1A Quick Recap of How ThreadLocal Stores Values

A ThreadLocal gives each thread its own copy of a value. It does not store the values itself. Each Thread object has a field called threadLocals, a small map called ThreadLocalMap, and when we call BUFFER.set(value) the value is put into the current thread's map, with the ThreadLocal object as the key.

Two details matter here. The key is held through a weak reference, so if nothing else references the ThreadLocal object, it can be garbage collected. But the value is held through a normal, strong reference from the map. So the value lives as long as the thread lives, or until we call remove(), or until the map happens to clean up an entry whose key was collected. Nothing removes it at the end of a request, because ThreadLocal does not know what a request is.

2The Broken Filter

Here is the code from the question, written out.

Java
public class BufferFilter implements Filter {
static final ThreadLocal<byte[]> BUFFER = new ThreadLocal<>();
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
BUFFER.set(new byte[1_000_000]); // 1 MB attached to the current thread
chain.doFilter(req, res); // the rest of the request uses BUFFER.get()
// no BUFFER.remove(): the array stays on the thread after the request
}
}

A servlet container such as Tomcat serves requests from a thread pool, 200 threads by default in Tomcat. A thread takes a request, runs the filter chain, returns to the pool and waits for the next request. Its ThreadLocalMap goes with it, so the array set during the last request is still there.

3Problem 1: Memory Held Forever by Every Pool Thread

Each pool thread that has ever served a request now holds a 1 MB array. With 200 threads, that is about 200 MB of heap that is never released while the threads exist, even when the service is idle. It is not an unbounded leak, since a thread's value is replaced on its next request, but it is a permanent cost that nobody planned for and that grows with the pool size.

The filter also allocates a new 1 MB array on every request. At 1,000 requests per second that is about 1 GB of allocation per second just for these buffers, which keeps the garbage collector busy. With G1, an array that is at least half a region in size is a humongous object allocated in its own regions, and with smaller heaps the region size can be 1 or 2 MB, so these arrays may be humongous; check your region size. Reusing the buffer per thread would at least avoid this churn, but only if we also accept the memory it holds.

4Problem 2: Leaking the Class Loader on Redeploy

Application servers can redeploy a web application without restarting the JVM. The old application's classes are loaded by its own class loader, and for the old classes to be unloaded, nothing may reference that class loader anymore. The server's pool threads, however, survive the redeploy.

In our exact example the value is a byte[], a JDK class, so the stale array wastes memory but does not pin the class loader. The danger appears as soon as the value is an instance of a class from the application, which is very common: a RequestContext object, a buffer wrapper, or a value created by a lambda from the application. Then the stale value in the pool thread references its class, the class references its class loader, and the class loader references every class of the old application and all their static fields. After a few redeploys, metaspace fills up with copies of the application. Tomcat detects this case on undeploy and logs a warning that a ThreadLocal value was not removed.

Step throughWhat a stale ThreadLocal value keeps alive
  1. Pool threadsurvives the redeploy
  2. ThreadLocalMap entrystrong reference to the value
  3. Value: RequestContexta class from the old application
  4. Old web app class loaderreferenced by the class
  5. Every old class and static fieldcannot be unloaded, metaspace grows

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

5Problem 3: Another User's Data

A buffer that is overwritten at the start of every request is fairly safe. But the same pattern is often used for request context, such as the current user, the tenant or a security token, and there the danger is serious. Suppose the filter sets the context only when a header is present.

Java
static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();
// request 1 on thread exec-7: header present
CURRENT_USER.set("alice"); // exec-7 now holds "alice"
// ... request finishes, no remove()
// request 2 on thread exec-7: header missing, so set() is skipped
String user = CURRENT_USER.get(); // "alice": request 2 runs as Alice

The second request runs with the first request's identity. It might read Alice's orders or write data under her name. These bugs are rare, depend on which thread serves which request, and almost never show up in tests, which makes them very hard to find.

6The Fix and Better Designs

The minimum fix is to remove the value in a finally block, so it is cleared whether the request succeeds or throws.

Java
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
BUFFER.set(new byte[1_000_000]);
try {
chain.doFilter(req, res);
} finally {
BUFFER.remove(); // the thread goes back to the pool clean
}
}
// JDK 25: a scoped value is bound only while the lambda runs
static final ScopedValue<RequestContext> CONTEXT = ScopedValue.newInstance();
ScopedValue.where(CONTEXT, new RequestContext(user)).run(() -> handle(request));
CONTEXT.isBound(); // false outside run(): nothing to clean up

Notice that remove(), not set(null), is the right call. set(null) leaves an entry in the map with a null value, while remove() deletes the entry.

Better still is to avoid the ThreadLocal. If the code that needs the buffer can receive it as a parameter, passing it explicitly makes the lifetime obvious. For request context that must reach deep code, scoped values, finalised in JDK 25, bind a value for the duration of a method call and unbind it automatically when the call returns, so there is nothing to forget. They also work well with virtual threads, where a ThreadLocal on each of millions of threads would be costly. And for the buffer itself, if allocation churn matters, a small bounded pool of buffers is clearer than per-thread buffers that live forever.

7Follow-up questions

Why does ThreadLocalMap use a weak reference for the key if the value still leaks?

The weak key lets the map notice that a ThreadLocal object is gone and clean up its entry later, during other get, set or remove calls on the same thread. But the clean-up is opportunistic and the value is strongly held until then, and in our case the ThreadLocal is a static field, so the key never becomes unreachable while the application runs. The weak key does not replace calling remove().

Does InheritableThreadLocal make this worse?

It can. InheritableThreadLocal copies values to child threads at creation time, so a pool thread created during a request can inherit that request's user and keep it for its whole life. With thread pools this is usually a bug rather than a feature.

8Conclusion

In this answer, we saw that a ThreadLocal value is stored in the thread's own map with a strong reference, so in a pooled servlet thread it outlives the request. Without remove(), each pool thread holds 1 MB forever, a value whose class comes from the application can pin the old class loader after a redeploy, and context values such as the current user can leak into the next request on that thread. The fix is remove() in a finally block, and better designs are passing data explicitly or using scoped values, final in JDK 25.

What to say in the interviewAbout 90 seconds aloud

Open with

The core problem is that a ThreadLocal value belongs to the thread, not the request, and container threads are pooled, so after the request the 1 MB array stays in that thread's ThreadLocalMap.

Then, if they want more

The map holds the value with a strong reference, so it only goes away with remove or when the thread dies. That gives three problems.

First, memory: every pool thread, say 200 in Tomcat, keeps 1 MB alive forever, around 200 megabytes, and the filter also allocates a megabyte per request, which is heavy GC churn and may even be humongous allocations in G1.

Second, redeploys: with a plain byte array the class loader is not pinned, but as soon as the value is an application class, like a request context, the stale value keeps its class and therefore the old web app class loader alive, and metaspace fills up after a few redeploys.

Third, correctness: if this pattern holds user data and a later request skips the set, it reads the previous user's value, so one user can act as another. The fix is to call remove in a finally block around chain.doFilter, not set null.

Better is to pass the buffer explicitly, or for request context use scoped values, which are final in JDK 25 and unbind automatically when the call ends.

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 servlet filter does BUFFER.set(new byte[1_000_000]) at the start of each request...": https://scrivio-interview-library.netlify.app/java/jvm-diagnostics/b247314175/