开发者

How this works, keeping static (global) reference to the request data

I need to know how this works:

HttpServletRequest request =  (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

This means that, some where when the server receive the request (actually the Faces APIs who do that) , it did something like:

FacesContext fx = new FacesContext();
fx.setRequest(httpServletRequest);
FacesContext.setCurrentInstance(fx);

so.. suppose this scenario:

one request sent ... the FacesContext object populated .. and then it waits 5 seconds (by any mean, for example using Thread.sleep() ) in this whil开发者_JS百科e .. another request sent who - by my understanding- will override the contents of the FacesContext.getCurrentInstance() object .. so when the previous request came from the sleep, it will read the overriden contents..

Is my understanding true???


No, this is not true. Every HTTP request/response cycle is executed in a single and fully dedicated thread. The FacesContext is created in the beginning of a request and stored as a ThreadLocal variable which is trashed when the response is finished. The getCurrentInstance() returns the ThreadLocal variable. Anywhere in the code which is executed in the same thread (read: the same request) will have access to the same FacesContext instance. Different requests run in their own threads with their own FacesContext instance. The creation and destroy of the FacesContext is managed by the FacesServlet.

See also:

  • java threadlocal singleton - what is it? - related answer
  • How do servlets work? Instantiation, sessions, shared variables and multithreading - explains servlet lifecycle
  • How to initialize an API in servlet environment - code example of how to implement ThreadLocal
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜