Encountered a strange problem with Spring MVC running on Tomcat 7 today. I had a with 1 max thread capacity on my application which wasn’t working as it supposed to. My Runnable task look something like this:
public class LongRunningTask implements Runnable { private HttpServletRequest request; public LongRunningTask(HttpServletRequest request) { this.request = request; } public void run() { // do something .. } }
Notice I originally added a reference to HttpServletRequest with the intention of obtaining the remote host and address of the client. My controller class look something like this:
public class HomeController { private ThreadPoolTaskExecutor taskExecutor; (...) public String schedule(HttpServletRequest req, ...) { taskExecutor.submit(new LongRunningTask(req)); } }
With the hope that user’s get their response immediately while the actual work is still queued on the background.
Turns out this caused all sorts of strange behavior. Sometime the task will run, most of the time it will just sit in the queue forever / won’t even queue at all.
After further research and trial and error, I figured out this was because my runnable is holding a reference to HttpServletRequest. When I refactored the code the task executor work as per normal again.
I’ve came into a conclusion that holding to a HttpServletRequest object for longer than necessary is not a good practice.