Why Passing HttpServletRequest to Async Threads Causes Bugs in Spring Boot
Passing a HttpServletRequest to a regular thread in Spring Boot causes Tomcat to recycle the request after the servlet returns, making parameters unavailable and yielding null values, so you must use the servlet async API (startAsync and complete) to keep the request alive.
When a HttpServletRequest is passed to a new thread, Tomcat may recycle the request after the original servlet method returns, causing parameters to become unavailable and leading to unexpected null values or missing query parameters.
The author reproduces the problem with a simple Spring Boot controller that starts a new thread and calls request.getParameter(...) . The first request works, but the second request fails because the request object has been recycled and the internal flag didQueryParameters is already true , so Tomcat skips parsing the query string.
Debugging Tomcat’s org.apache.catalina.connector.Request and org.apache.tomcat.util.http.Parameters reveals that Tomcat reuses request objects via the recycle() method, and parameter parsing occurs only once per request unless asynchronous processing is enabled.
The Servlet specification states that a request is valid only within the servlet’s service method unless startAsync() is invoked. When startAsync() is used, the request remains alive until AsyncContext.complete() is called.
Correct usage is to start asynchronous processing with request.startAsync() , perform work in another thread, and finish with asyncContext.complete() . This prevents premature recycling of the request.
Key takeaway: avoid passing HttpServletRequest to ordinary threads; use the servlet async API for safe asynchronous operations.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.