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

邮差的信 提交于 2019-12-10 19:16:51

问题


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


回答1:


That's what it was made for. But take care to remove the ThreadLocal on the end of the context, else you might run in memory leaks, or at least hold unused data for too long.

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




回答2:


That depends on the scope of the data. The ThreadLocal will be specific to the request thread, not specific to the user's session (each request, a different request processing thread may be used). Hence it will be important to remove the data as the request processing is completing (so that it doesn't bleed over into some other user's session when that same thread services their request).




回答3:


If you are completing a request/response pair with a single thread, then it works fine in my experience. However, "event driven" webapps are coming into vogue with the rise of ajax and high performance containers. These event driven models allow for a request thread to be returned to their thread pool, e.g. during I/O events, so that the thread is not occupied waiting for an external service call to return. As a result, a single logical request may be serviced by multiple different threads. Event driven architecture, coupled with NIO on the server side can yield highly improved throughput.

With that said, if your application doesn't have this architecture, it seems reasonable to me.

If you're not familiar with this model, take a look at Tomcat 6's "comet" and Jetty 6's Continuations. These are vendor-specific implementations of asynchronous I/O pending official Servlet 3.0 support. Note that Tomcat 7 claims to be fully 3.0 compliant now.




回答4:


ThreadLocal in a multithreaded program is much the same as a static/global in a non-threaded program. That is to say, use of ThreadLocal is an abomination.




回答5:


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

In the web-tier of a web application use the session context (or other on top framework specific contexts) to store data and state over request scope.

If you introduce a business layer it should not be dependent on a specific web-context of course. spring and Java EE provide solutions for security, transactions and persistence as a context.

If you touch this manually you should be really careful; it can lead to cleanup problems, memory leaks, and strange bugs...



来源:https://stackoverflow.com/questions/4866006/is-it-a-good-idea-to-use-threadlocal-as-a-context-for-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!