Previous | Next | Trail Map | Servlets | The Life Cycle of a Servlet

Destroying a Servlet

The destroy method provided by the HttpServlet class destroys the servlet and logs the destruction. To destroy any resources specific to your servlet, override the destroy method. The destroy method should undo any initialization work and synchronize persistent state with the current in-memory state.

The following example shows the destroy method that accompanies the init method in the previous lesson:

    public class BookDBServlet extends GenericServlet {

        private BookstoreDB books;

        ... // the init method

        public void destroy() {
            // Allow the database to be garbage collected
            books = null;
        }
    }

A server calls the destroy method after all service calls have been completed, or a server-specific number of seconds have passed, whichever comes first. If your servlet handles any long-running operations, service methods might still be running when the server calls the destroy method. You are responsible for making sure those threads complete. The next lesson shows you how.

The destroy method shown above expects all client interactions to be completed when the destroy method is called, because the servlet has no long-running operations.


Previous | Next | Trail Map | Servlets | The Life Cycle of a Servlet