Tutorials Logic, IN info@tutorialslogic.com

Servlet Lifecycle init, service, destroy Methods

Servlet Instance Lifecycle

The container loads a servlet class, creates an instance, calls init once, invokes service concurrently for requests, and calls destroy before graceful removal. The same servlet instance commonly serves many threads, which makes mutable instance fields unsafe for request state.

Servlet Lifecycle Overview

The Servlet container manages the complete lifecycle of a Servlet. The lifecycle consists of three main phases:

The container creates only one instance of each Servlet and handles concurrent requests using multiple threads. This is why Servlet instance variables must be thread-safe.

  • Initialization - init() is called once when the Servlet is first loaded
  • Request Handling - service() is called for every client request
  • Destruction - destroy() is called once when the Servlet is removed from service

Servlet Lifecycle Methods

Servlet Lifecycle Methods
package com.example;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.WebServlet;
import java.io.*;
import java.util.concurrent.atomic.AtomicInteger;

@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {

    // Use AtomicInteger for thread-safe counter
    private AtomicInteger requestCount = new AtomicInteger(0);
    private String initMessage;

    // ===== PHASE 1: INITIALIZATION =====
    // Called ONCE when servlet is first loaded (or at startup if load-on-startup is set)
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // Read init parameters
        initMessage = config.getInitParameter("message");
        if (initMessage == null) initMessage = "Default message";
        System.out.println("[INIT] LifecycleServlet initialized. Message: " + initMessage);
    }

    // ===== PHASE 2: REQUEST HANDLING =====
    // service() dispatches to doGet/doPost/etc. based on HTTP method
    // You can override service() directly, but it's better to override doGet/doPost
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("[SERVICE] Handling request #" + requestCount.incrementAndGet());
        super.service(req, resp); // Delegates to doGet/doPost/etc.
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<h2>Servlet Lifecycle Demo</h2>");
        out.println("<p>Init message: " + initMessage + "</p>");
        out.println("<p>Total requests: " + requestCount.get() + "</p>");
        out.println("<p>Thread: " + Thread.currentThread().getName() + "</p>");
    }

    // ===== PHASE 3: DESTRUCTION =====
    // Called ONCE when servlet is removed (server shutdown or undeploy)
    @Override
    public void destroy() {
        System.out.println("[DESTROY] LifecycleServlet destroyed. Total requests served: "
                + requestCount.get());
        // Release resources: close DB connections, stop threads, etc.
    }
}

load-on-startup and Lazy Loading

By default, Servlets are loaded lazily - on the first request. You can force eager loading at startup using load-on-startup:

  • Negative value (default): Lazy loading - loaded on first request
  • 0 or positive: Eager loading - loaded at container startup. Lower numbers load first.

load-on-startup Configuration

load-on-startup Configuration
// loadOnStartup = 1 means load at startup, priority 1 (loads before priority 2, 3, etc.)
@WebServlet(urlPatterns = "/app", loadOnStartup = 1)
public class AppInitServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        // This runs at server startup
        System.out.println("Application initialized at startup");
        // Initialize shared resources: DB connection pool, caches, etc.
        getServletContext().setAttribute("appStartTime", System.currentTimeMillis());
    }
}

load-on-startup and Lazy Loading - XML Configuration

load-on-startup and Lazy Loading - XML Configuration
<servlet>
    <servlet-name>AppInitServlet</servlet-name>
    <servlet-class>com.example.AppInitServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
    <servlet-name>DataServlet</servlet-name>
    <servlet-class>com.example.DataServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

Initialization and Shutdown

Use init for small configuration validation or for creating a resource the servlet clearly owns. Prefer container-managed shared services for pools and executors. If initialization fails, throw a ServletException with safe context so the application does not accept requests in a partially usable state.

destroy should release owned resources and stop bounded background work, but a process crash may skip it. Local variables belong to one invocation; immutable servlet fields can hold configuration or thread-safe collaborators. Test concurrent requests when any collaborator has mutable state.

Concurrency, Requests, and Lifecycle Ownership

A container normally creates one servlet instance and calls service for many requests, often on different threads at the same time. Request-specific data therefore belongs in method-local variables, request attributes, or other request-scoped objects, not mutable servlet instance fields.

Use init for validated, thread-safe resources shared by requests. Use destroy to close resources owned by that servlet after the container stops routing new requests. Dependency pools are usually container-managed and should be released according to their owner rather than closed per request or from an unrelated servlet.

  • Do not store HttpServletRequest, HttpSession, users, counters, or temporary buffers in mutable instance fields.
  • Immutable configuration read during init is safe to share after publication.
  • Use thread-safe collaborators or explicit synchronization for genuinely shared mutable state.
  • Do not create a new thread per request; use container-supported asynchronous processing or managed executors.
  • destroy is for cleanup, not for work that must be guaranteed after a crash or forced shutdown.

Startup Failure and Container Control

Throw ServletException from init when required configuration or a required resource is unavailable. The container then keeps the servlet out of service instead of accepting requests with a partially initialized object. Load-on-startup can move this validation to deployment time; lazy initialization delays it until the first request.

The container owns lifecycle calls. Application code must not call init, service, or destroy directly. Test lifecycle-dependent logic by extracting it into ordinary collaborators and testing the servlet boundary with container-aware integration tests or request and response doubles.

Before you move on

Servlet Lifecycle init, service, destroy Methods Mastery Check

5 checks
  • The Servlet container manages the complete lifecycle of a Servlet.
  • The lifecycle consists of three main phases.
  • The container creates only one instance of each Servlet and handles concurrent requests using multiple threads.
  • This is why Servlet instance variables must be thread-safe.
  • By default, Servlets are loaded lazily - on the first request.
Next Step
Next Practice

Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.