简体   繁体   中英

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<>();

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.

If you put something in a ThreadLocal in a Thread that is not 100% under your control (ie 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM