I have a servlet that handles a particular incoming request. We’ll call it `UpdateUserStats’. I want the call to be fast, but I also need the request to do a reasonably expensive task. I thought that it might be a nice solution if I let the UpdateUserStats servlet do all of the work that determines success or failure, persist the new state, and then enqueue some work for a background thread to take care of and return success immediately.
This seems nice, but I’m wondering how to handle shutdown. When the server shuts down, I want to make sure that it doesn’t kill the background thread until no more work remains. I was thinking of using a tomcat ServletContextListener to let the background thread know that the server is going down and it is alright to quit out once the queue ends, but I’m not 100% sure of how this will behave. Will contextDestroyed() only after all requests are done processing? The interface seems to imply this, but I didn’t find it in the documentation. Also, I wonder how long Tomcat is willing to wait around before getting angry that a background thread isn’t terminating.
Alternately, is there a better way to handle this problem? It’s a Spring app if perhaps Spring has some magic post-request background work functionality.
Based on servlet spec documentation
“On application shutdown, listeners are notified in reverse order to their declarations
with notifications to session listeners preceeding notifications to context listeners.
Session listeners must be notified of session invalidations prior to context listeners
being notified of application shutdown.”
So this should be the first listener which handles notifying the thread to complete its job.
I have used tomcat and as far a I have seen, it would not wait for more than 10-15 seconds before giving up doing a clean shutdown if the listener does not finish by then.
Typically all containers like Spring use listener for a clean exit during shutdown