When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources, or when it is being shut down), it calls the
destroymethod of the
Servletinterface. In this method, you release any resources the servlet is using and save any persistent state. The following
destroymethod releases the database object created in the
initmethod described in Initializing a Servlet:
All of a servlet's
servicemethods should be complete when a servlet is removed. The server tries to ensure this completion by calling the
destroymethod only after all service requests have returned or after a server-specific grace period, whichever comes first.
If your servlet has potentially long-running service requests, use the techniques described below to do the following:
- Keep track of how many threads are currently running the
- Provide a clean shutdown by having the
destroymethod notify long-running threads of the shutdown and wait for them to complete.
- Have the long-running methods poll periodically to check for shutdown and, if necessary, stop working, clean up, and return.