Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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<>();
like image 870
deepak PATRA Avatar asked Mar 03 '23 10:03

deepak PATRA


2 Answers

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.

like image 169
Adisesha Avatar answered Mar 11 '23 14:03

Adisesha


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.

like image 44
racraman Avatar answered Mar 11 '23 12:03

racraman