Java Academy Logo

Java Academy

Servlet Lifecycle in Java

Every Servlet passes through a well-defined lifecycle managed by the web container. Understanding init(), service(), and destroy() helps you write efficient, thread-safe web applications.

Lifecycle Phases

  • Loading and Instantiation — The container loads the Servlet class and creates one instance (Singleton by default).
  • Initialization — init(ServletConfig) is called once before any request is handled.
  • Request Handling — service() (or doGet/doPost) is called for each client request.
  • Destruction — destroy() is called when the container shuts down or undeploys the application.

init() Method

The init() method runs exactly once when the Servlet is first loaded. Use it to read configuration from web.xml or @WebInitParam annotations, open database connection pools, or initialize expensive resources. Never perform heavy initialization in the constructor.

service() Method

For every HTTP request, the container calls service(), which dispatches to doGet(), doPost(), doPut(), or doDelete() based on the HTTP method. Servlets must be thread-safe: instance variables shared across requests can cause race conditions.

destroy() Method

When the application is undeployed or the server stops, destroy() releases resources—closing connections, flushing caches, and stopping background threads. Always clean up resources opened in init().

Lifecycle Code Example

public class LifecycleServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        System.out.println("Servlet initialized");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().println("Handling request");
    }

    @Override
    public void destroy() {
        System.out.println("Servlet destroyed");
    }
}

Frequently Asked Questions

How many Servlet instances are created?

Typically one instance per Servlet class per JVM. The container creates multiple threads to handle concurrent requests against that single instance, which is why thread safety matters.

Continue Learning