Is the flow guaranteed for the entire request processed by the servlet?

I came across a situation where I use the static variable ThreadLocal to store a bean that contains different values ​​of indicators from different classes during the request life cycle. In the filter, I create a bean and set it to a local stream variable and delete it from the local stream variable in the same filter after processing the request. I got confused that the bean contains values ​​from other queries! The only explanation for this is a thread that is shared to process multiple requests at once. So, the question is in the name.

+3
source share
3 answers

Although a single thread typically processes one request (speaking of tomcat, for sure), a thread can process several requests over time, but not until the end of the current request, unless you use include / forward alike.

I would highly recommend that you use the (setAttribute ()) attribute of the specified w / your bean request and use it for profiling. If you cannot provide a request to various methods ... well, you are stuck with ThreadLocal [this is not a bad solution].

Alternatively, you can publish the code as you install / uninstall threadLocal bean.

Keep in mind that you need some control over this bean (it will not be available outside of the request).

Edit: forgot to ask: do you use try / finally call doFilter (...)?

the code should be such that

installBean();
try{
  chain.doFilter(req, resp);
}finally{
 Bean b = deinstallBean();
 useTheMetrics(b);
//potentially, process exception, etc
}
+6
source

, , . , , ThreadLocal , , .

+2

Yes, you can assume that one thread will process each request.

Use the unit finallyto clean (install in null) ThreadLocalthe filter after processing the rest of the chain. This will prevent data from previous queries from matching the current query.

+1
source

Source: https://habr.com/ru/post/1788067/


All Articles