Menu

Clearing per-request ThreadLocal state in a Java web app
📰

Clearing per-request ThreadLocal state in a Java web app

DEV Community: java·Darkø Tasevski·about 18 hours ago
#QRoMudGX
#devtojava#devto#dev#parameters#thread
Long article (1454 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.