[英]java ThreadLocal proplem
private HttpServletRequest request;
private static ThreadLocal<WebContext> wcHolder = new ThreadLocal<WebContext>();
private WebContext(){}
public static WebContext newInstance(HttpServletRequest request){
//case 1:correct
// WebContext wc = new WebContext();
// wc.request = request;
//case 2:incorrect
//(to resolve multiply creat WebContext object within one request)
WebContext wc = wcHolder.get();
if(wc==null){
wc = new WebContext();
wc.request = request;
wcHolder.set(wc);
}
return wc;
}
case 1 is correct. 案例1是正确的。
but case 2 但案例2
the question is: 问题是:
ps:sorry,my english is bad. ps:对不起,我的英语不好。 :)
:)
- is one ThreadLocal bind on Thread not right?
Thread上的一个ThreadLocal绑定不对吗?
A ThreadLocal
binds a separate object to each thread, yes. ThreadLocal
将单独的对象绑定到每个线程,是的。 That's its purpose. 这是它的目的。
- is one tomcat request is one Thread not right?
是一个tomcat请求是一个线程不对吗?
Each request is handled by exactly one thread, but I'm fairly certain that Tomcat does not spawn a new thread for each request. 每个请求都由一个线程处理,但我相当确定Tomcat不会为每个请求生成一个新线程。 It uses a thread pool.
它使用线程池。
Also, different requests in the same session may be served by different threads. 此外,同一会话中的不同请求可以由不同的线程服务。
- how correct above code ?
上面的代码有多正确?
If the previous answers don't explain it then I don't know, because it's not clear in what way you consider the behavior you observe to be incorrect. 如果以前的答案没有解释,那么我不知道,因为你不清楚你认为你认为不正确的行为的方式。
Nevertheless, if your intent is for each request to have exactly one WebContext
, unique to it, then ThreadLocal
s seem a poor choice for managing that. 然而,如果你的意图是每个请求只有一个
WebContext
,它是唯一的,那么ThreadLocal
似乎是管理它的糟糕选择。 Request attributes, on the other hand, are designed for exactly that purpose. 另一方面,请求属性是为了这个目的而设计的。 See ServletRequest.getAttribute() , ServletRequest.setAttribute() , etc. .
请参阅ServletRequest.getAttribute() , ServletRequest.setAttribute() 等 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.