This one is about a ThreadLocal in an older Java web app (Spring MVC on Tomcat, pages rendered by running XML through XSLT), and about where the code that cleans it up should live, which took me more attempts than I'd like to admit to get right.

The task itself was small, we needed a couple of new XSLT parameters for one page. The XSLT engine in that app is a singleton bean, and since the parameters differ per request, someone a long time ago put them in a ThreadLocal, which looks roughly like this:

public class XsltEngine { private final ThreadLocal<HashMap<String, Object>> parameters = new ThreadLocal<>(); public void addParameter(String name, Object value) { HashMap<String, Object> map = parameters.get(); if (map == null) { map = new HashMap<>(); } map.put(name, value); parameters.set(map); } public void addParameters(Map<String, ?> values) { HashMap<String, Object> map = parameters.get(); if (map == null) { map = new HashMap<>(); } map.clear(); map.putAll(values); parameters.set(map); } @PreDestroy void clearParameters() { HashMap<String, Object> map = parameters.get(); if (map == null) { map = new HashMap<>(); } map.clear(); parameters.set(map); } // transform(...) copies the current thread's map onto the Transformer } 

Two things are wrong here, and neither shows up until you think about who runs this code.

First, nothing ever calls parameters.remove(). Tomcat serves requests from a thread pool, so a thread that rendered user A's page keeps user A's map after the response is sent, and the next request that thread picks up (possibly from user B) starts with it. The app got away with this because almost every render path began with addParameters(...), which clears the map and refills it, so "start clean" was a habit of each handler and not something the engine guaranteed.

Second, the @PreDestroy method looks like the cleanup, but it runs once, when the container destroys the bean, on whatever thread does the shutdown, and a ThreadLocal only ever touches the copy that belongs to the current thread. So it "clears" the shutdown thread's map (it even creates one if there wasn't any) and leaves every request thread's map exactly as it was.

A ThreadLocal can only be cleaned from the thread that owns the value, so the cleanup has to run on the request thread, at the end of the request.

The handler that leaked

There was one handler, the one that renders a related form (a small form opened from a parent record), that never called addParameters before rendering. It added a few values of its own on top of whatever was already on the thread, which meant it rendered with the previous request's parameters, which could include values from another user's request. Most of those values didn't visibly change the output, which is probably why nobody noticed, but "probably harmless" is not a great place to be with another user's data.

The first fix was the obvious local one, reset the parameters in that handler like the other handlers do. That worked, but the reset built the map from a helper that only knew about some of the parameters, and the related form had been getting one of the missing ones (a flag that picks between the old and the new page header) from the previous request by accident. After the reset it always fell back to the XSL default, so related forms suddenly showed the old header, and a second commit had to seed the related form with the same parameters the main render path uses. Fixing one handler had only made the leak visible in a different way, the root cause (nothing clears the thread at the end of a request) was still there.

Moving the cleanup next to the writer

The textbook answer for request-scoped ThreadLocals is to clear them at the request boundary, so the next attempt was a servlet filter on /* and a public clearParameters() that calls remove():

public class XsltParametersCleanupFilter extends HttpFilter { private final XsltEngine xsltEngine; @Override protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(req, res); } finally { xsltEngine.clearParameters(); } } } 
public void clearParameters() { parameters.remove(); } 

This is correct, and it covers every path, but a colleague asked in review why the lifecycle of the engine's parameters lived in a filter that knows nothing about rendering. Counting them showed that every addParameter/addParameters call in the app (a few dozen of them) was in one service class, and that class had only three public methods that set parameters: the main renderPage, a lookup dialog handler, and the related-form handler, the last two called directly by their own actions and not through renderPage. The export actions also call transform, but they don't read anything left on the thread.

So the state has exactly one writer, and the place to clean it up is that writer, at each of its entry points:

@Override public String renderPage(RenderParams params) { try { return render(params); } finally { xsltEngine.clearParameters(); } } @Override public void showLookUp(Connection connection, RenderParams params, String itemId, int lookupLevel, RenderContext context) throws SQLException { try { lookUp(connection, params, itemId, lookupLevel, context); } finally { xsltEngine.clearParameters(); } } @Override public void showRelatedForm(Connection connection, String itemId, RenderContext context) throws SQLException { try { loadForm(connection, context, itemId); seedMainRenderParameters(context); renderForm(context); } finally { xsltEngine.clearParameters(); } } 

For the two long methods the old body just moved into a private render and lookUp, so the diff stays small and readable. The filter, its registration and its tests got deleted (the final commit was +99/-161, which is my favourite kind of fix), and the tests that replaced them check that every entry point clears the engine, and for the main render and the related form also that it still clears when the render throws (a finally that nobody tested on the failure path is a bit of a promise).

The difference between the filter and the finally blocks is mostly about who has to remember what. With the filter, the cleanup is far away from the code that creates the state, and someone reading the engine has no idea it exists. With the finally blocks, anyone adding a fourth public method to that service sees right away that the other three clear the engine, and the rule ("a method that writes parameters ends by clearing them") lives next to the only code it applies to.

A per-render map instead

The cleanest version wouldn't have thread-local parameters at all. Each render would carry its own parameter map (on the per-render context object, say) and pass it into transform, so there'd be nothing left behind and nothing to clear. That means changing the engine's API and all of those call sites, which was too much for a PR that was supposed to add two parameters, so it stays as the next step and not this one.

The fix that stuck was the one that put the cleanup where the state is written. A ThreadLocal that holds request state needs a remove() on the same thread at the end of every unit of work that sets it, a @PreDestroy or any other shutdown hook can't do that because it runs on the wrong thread, and when one class is the only writer, a finally at each of its entry points keeps that rule in plain sight, where a request filter hides it from anyone reading the code that writes the values.