Is it a good idea to use ThreadLocal as a context for data?

Can ThreadLocal be used as a context for data in a web application?

+3
source share
5 answers

Why was this done. But take care to remove ThreadLocal at the end of the context, otherwise you could trigger a memory leak or at least hold unused data for a long time.

ThreadLocals are also very fast, you can think of it as a HashMap<Thread,Object> , which is always requested using Thread.getCurrentThread() .

+6
source

It depends on the amount of data. ThreadLocal will be specific to the request stream, and not to the user session (each request can use a different request processing thread). Therefore, it is important to delete data at the end of the request processing (so that it does not go to another user session when the same thread is serving their request).

+6
source

If you complete a request / response pair with a single thread, then it works fine in my experience. However, event-driven web applications are coming into fashion with the rise of ajax and high-performance containers. These event-driven models allow you to return a request stream to their thread pool, for example. during I / O events so that the thread is not busy waiting for the external service call to return. As a result, a single logical request can be served by several different threads. An event-driven architecture combined with server-side NIOs can provide high performance.

With that said, if your application does not have this architecture, it seems reasonable to me.

If you are not familiar with this model, take a look at Comet Tomcat 6 and Continuations. These are vendor-specific implementations of asynchronous I / O pending official support for Servlet 3.0. Please note that Tomcat 7 claims to be fully compatible with 3.0 now.

+2
source

ThreadLocal in a multithreaded program is almost the same as static / global in a non-threaded program. That is, using ThreadLocal is an abomination.

+1
source

In general, I would say no. Use frameworks to do this for you.

At the web tier of the web application, use the session context (or others in the context of the context of a particular structure) to store data and the status request area.

If you enter a business layer, it, of course, should not depend on the specific web context. spring and Java EE provide security, transaction, and contextual solutions.

If you touch this manually, you must be very careful; this can lead to cleaning problems, memory leaks and strange errors ...

+1
source

All Articles