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.
but case 2
the question is:
ps:sorry,my english is bad. :)
- is one ThreadLocal bind on Thread not right?
A ThreadLocal
binds a separate object to each thread, yes. That's its purpose.
- is one tomcat request is one Thread not right?
Each request is handled by exactly one thread, but I'm fairly certain that Tomcat does not spawn a new thread for each request. 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. Request attributes, on the other hand, are designed for exactly that purpose. See ServletRequest.getAttribute() , ServletRequest.setAttribute() , etc. .
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.