deepak PATRA
deepak PATRA

Reputation: 91

Thread local behaviour in spring boot

As we know Tomcat has approx 200 threads and Jetty has some default count threads in their respective thread pools. So if we set something in a ThreadLocal per request, will it be there in the thread for life time or will Tomcat clear the ThreadLocal after each request.

If we set something in userContext in a filter do we need to clear it every time the filter exits?

Or will the web server create a new thread every time, if we don't have a thread pool configuration?

public static final ThreadLocal<UserContextDto> userContext = new ThreadLocal<>();

Upvotes: 7

Views: 15449

Answers (3)

Adisesha
Adisesha

Reputation: 5258

Yes, you need to clear ThreadLocal. Tomcat won't clear ThreadLocals.

No, new thread is not created every time. A thread from the pool is used to serve a request, and returned back to pool once request is complete.

This not only applies to Tomcat, it applies to Jetty and Undertow as well. Thread creation for every request is expensive in terms of both resources and time.

Upvotes: 10

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

If you put something in a ThreadLocal in a Thread that is not 100% under your control (i.e. one in which you are invoked from other code, like for a HTTP request), you need to clear whatever you set before you leave your code.

A try/finally structure is a good way to do that.

A threadpool can't do it for you, because the Java API does not provide a way to clear a thread's ThreadLocal variables. (Which is arguably a shortcoming in the Java API)

Not doing so risks a memory leak, although it's bounded by the size of the thread pool if you have one.

Once the same thread gets assigned again to the code that knows about the ThreadLocal, you'll see the old value from the previous request if you didn't remove it. It's not good to depend on that. It could lead to hard to trace bugs, security holes, etc.

Upvotes: 0

racraman
racraman

Reputation: 5034

No, Tomcat will not clear ThreadLocals that your code creates, which means they will remain and could pollute subsequent requests.

So whenever you create one, make sure you clear it out before that same request or whatever exits.

It should also be noted that subsequent requests - even using the identical URL - could well be executed in a totally different thread, so ThreadLocals are not a mechanism for saving state between requests. For this, something like SessionBeans could be used.

Upvotes: 1

Related Questions