简体   繁体   中英

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.

but case 2

  1. first tomcat request..
  2. second request may get the WebContext object which belong to first req.
  3. when step 2 happened,WebContext's request object had diabled.
  4. then problem happened when operate on the wc and the request object!

the question is:

  1. is one ThreadLocal bind on Thread not right?
  2. is one tomcat request is one Thread not right?
  3. how correct above code ?

ps:sorry,my english is bad. :)

  1. is one ThreadLocal bind on Thread not right?

A ThreadLocal binds a separate object to each thread, yes. That's its purpose.

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM