Is it a good idea to use ThreadLocal as a context

2019-07-02 03:08发布

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

5条回答
Animai°情兽
2楼-- · 2019-07-02 03:32

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...

查看更多
冷血范
3楼-- · 2019-07-02 03:35

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

查看更多
闹够了就滚
4楼-- · 2019-07-02 03:38

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楼-- · 2019-07-02 03:47

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).

查看更多
对你真心纯属浪费
6楼-- · 2019-07-02 03:55

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.

查看更多
登录 后发表回答