Hello,
In the Tomcat container, do all the filters associated to a servlet and the servlet itself use the same thread? i.e, will doFilter() be run in the same thread as a servlet's service() method? Thanks in advance.
views:
63answers:
3Yes, each request is performed in a single thread, including all filters and the target servlet.
Yeah, each request is performed within a single servlet instance.Servlet container receives each request and start a new thread which contains the HttpServletRequest and HttpServletResponse. This thread process the request in the service method of the servlet instance and will be dstroyed as soon as the service method completes.
I suspect the question is more: Can I use ThreadLocal objects to pass data between filters and to servlets? In which case the answer is, absolutely. App servers do this themselves to track security, transaction, connection and other request information.
Just make sure you clean out your ThreadLocal in a finally block in the same code that sets the ThreadLocal.
As already noted by other, the servlets themselves may or may not be synchronized, but that is orthogonal to the concept of thread state; i.e. how many threads execute against object foo vs. can I put state in the thread and have it seen by object foo. The answer to the second question is always yes.
The only time the answer would be 'no' is if you made use of any asynchronous communication:
- Dispatched the call via AsyncContext
- mixed in EJBs and started making use of @Asynchronous or the TimerService
These involve the app server starting new threads not associated with the original request thread so any ThreadLocal state will not travel with the new thread. It is also why those APIs do not allow security and transaction context of the caller to be propagated to the method invoked as the caller and method are in different threads.
Advanced note, InheritableThreadLocal typically does not work as async calls are typically done by the server against a thread pool rather than creating child threads of the caller thread.