Servlet Lifecycle in Java
The servlet lifecycle in Java is the fixed sequence of steps a web container follows for every servlet: it creates one instance, calls init() once, calls service() for each request, and finally calls destroy() once. Knowing this sequence tells you where to open resources, where to handle requests, where to clean up, and why servlet fields must be thread-safe.
This lesson traces each stage with log output from Tomcat 11, shows how to load a servlet at startup and pass it settings, and ends with a servlet that loads a cache at startup, refreshes it in the background and shuts down cleanly. It builds on Java Servlet Basics.
The Five Stages of the Servlet Lifecycle
| Stage | Method | Called | Typical work |
|---|---|---|---|
| 1. Load and instantiate | Constructor | Once | Nothing heavy; the container controls timing |
| 2. Initialize | init() | Once, before any request | Read settings, open pools, load caches |
| 3. Handle requests | service() → doGet, doPost, ... | Once per request, on many threads | Read the request, write the response |
| 4. Take out of service | destroy() | Once, at undeploy or shutdown | Close resources, stop background threads |
| 5. Garbage collection | — | When the JVM decides | Nothing to do |
deploy or first request
│
▼
┌────────────────────────┐
│ new MyServlet() │ once
└───────────┬────────────┘
▼
┌────────────────────────┐
│ init(ServletConfig) │ once
└───────────┬────────────┘
▼
┌────────────────────────┐ ◄── request 1 (thread A)
│ service(req, resp) │ ◄── request 2 (thread B)
│ → doGet / doPost ... │ ◄── request 3 (thread A)
└───────────┬────────────┘
▼ undeploy / shutdown
┌────────────────────────┐
│ destroy() │ once
└────────────────────────┘
How it works:
- The container creates one instance per servlet declaration, not one per request. All requests share it.
service()is never called beforeinit()finishes, and never called again afterdestroy()starts.
Watch the Servlet Lifecycle in Action
This servlet prints a line at every stage, so you can see when the container calls each method.
package com.gocourse.portal;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
@WebServlet("/lifecycle")
public class LifecycleServlet extends HttpServlet {
private final AtomicInteger requestCount = new AtomicInteger();
public LifecycleServlet() {
System.out.println("1. constructor thread=" + Thread.currentThread().getName());
}
@Override
public void init() throws ServletException {
System.out.println("2. init() thread=" + Thread.currentThread().getName());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
int number = requestCount.incrementAndGet();
System.out.println("3. doGet() #" + number + " thread=" + Thread.currentThread().getName());
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println("Request number " + number);
}
@Override
public void destroy() {
System.out.println("4. destroy() after " + requestCount.get() + " requests");
}
}
Run Tomcat in the foreground, deploy the WAR, send three requests, then delete the WAR:
$CATALINA_HOME/bin/catalina.sh run # terminal 1
cp target/student-portal.war $CATALINA_HOME/webapps/ # terminal 2
for i in 1 2 3; do curl -s http://localhost:8080/student-portal/lifecycle; done
rm $CATALINA_HOME/webapps/student-portal.war
Output in terminal 1 (Tomcat log lines removed):
1. constructor thread=http-nio-8080-exec-1
2. init() thread=http-nio-8080-exec-1
3. doGet() #1 thread=http-nio-8080-exec-1
3. doGet() #2 thread=http-nio-8080-exec-2
3. doGet() #3 thread=http-nio-8080-exec-3
4. destroy() after 3 requests
Output in terminal 2:
Request number 1
Request number 2
Request number 3
How it works:
- Nothing is printed at deployment. By default the container creates the servlet lazily, on the first request that maps to it.
- The constructor and
init()run on the thread of that first request, which therefore takes a little longer. - Each request may run on a different worker thread (
exec-1,exec-2, ...), but it is always the same object, sorequestCountkeeps growing. - Removing the WAR undeploys the app, and the container calls
destroy()once.
Load a Servlet at Startup With loadOnStartup
Slow work in init(), such as loading a large file, makes the first user wait. loadOnStartup tells the container to create and initialize the servlet while the app deploys.
@WebServlet(urlPatterns = "/report", loadOnStartup = 1)
public class ReportServlet extends HttpServlet {
@Override
public void init() {
long start = System.nanoTime();
// Simulate loading report templates
try { Thread.sleep(800); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
System.out.printf("ReportServlet ready in %d ms on %s%n",
(System.nanoTime() - start) / 1_000_000, Thread.currentThread().getName());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.getWriter().println("Report service is running");
}
}
Output in the Tomcat terminal during deployment, before any request:
ReportServlet ready in 801 ms on Catalina-utility-1
loadOnStartup value | Behaviour |
|---|---|
| Not set or negative | Load lazily on the first request |
0 or positive | Load during deployment |
| Lower number | Loaded earlier than servlets with higher numbers |
How it works:
- The init now runs on Tomcat's deployment thread (
Catalina-utility-1), not on a request thread. - In
web.xmlthe same setting is<load-on-startup>1</load-on-startup>inside<servlet>. - If
init()fails at startup, you see the error in the deployment log right away, instead of when a user first visits.
init() vs init(ServletConfig)
GenericServlet, the parent of HttpServlet, has two init methods. The container calls init(ServletConfig), which saves the config and then calls the no-argument init().
| Override | Must call super? | getServletConfig() works? |
|---|---|---|
init() | No | Yes |
init(ServletConfig config) | Yes, super.init(config) | Only if super.init(config) was called |
@WebServlet("/broken")
public class BrokenInitServlet extends HttpServlet {
@Override
public void init(jakarta.servlet.ServletConfig config) {
// Missing super.init(config)!
System.out.println("Servlet name: " + config.getServletName());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// getServletConfig() returns null, so getServletName() throws an exception
response.getWriter().println("Hello from " + getServletName());
}
}
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/student-portal/broken
Output:
500
How it works:
getServletName(),getInitParameter()andgetServletContext()all read the saved config. Withoutsuper.init(config)it isnull, so the first call throws an exception (IllegalStateExceptionorNullPointerException, depending on the API version) and the client gets500.- Overriding the no-argument
init()avoids this problem completely, so prefer it.
Pass Settings With Servlet Init Parameters
Init parameters are name–value settings given to one servlet. Read them in init(), so the servlet is configured before the first request.
@WebServlet(
urlPatterns = "/greeting",
initParams = {
@WebInitParam(name = "greeting", value = "Welcome to GOCOURSE"),
@WebInitParam(name = "maxNameLength", value = "20")
})
public class GreetingServlet extends HttpServlet {
private String greeting;
private int maxNameLength;
@Override
public void init() throws ServletException {
greeting = getInitParameter("greeting");
try {
maxNameLength = Integer.parseInt(getInitParameter("maxNameLength"));
} catch (NumberFormatException e) {
throw new ServletException("maxNameLength must be a number", e);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String name = request.getParameter("name");
if (name == null || name.isBlank()) name = "learner";
if (name.length() > maxNameLength) name = name.substring(0, maxNameLength);
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println(greeting + ", " + name + "!");
}
}
curl "http://localhost:8080/student-portal/greeting?name=Asha"
curl "http://localhost:8080/student-portal/greeting?name=AVeryVeryLongStudentName"
Output:
Welcome to GOCOURSE, Asha!
Welcome to GOCOURSE, AVeryVeryLongStudent!
How it works:
@WebInitParamsets default values. A<servlet>entry with the same name inweb.xmlcan override them with<init-param>without recompiling.- The fields are written once in
init()and only read afterwards. Becauseinit()finishes before any request runs, all request threads see the values safely. - Throwing
ServletExceptionfrominit()stops the servlet from entering service, so a bad setting is caught early.
Application-Wide Startup With ServletContextListener
init() and destroy() belong to one servlet. For work that the whole application needs, such as a shared connection pool, use a ServletContextListener. It runs before any servlet is initialized and after every servlet is destroyed.
package com.gocourse.portal;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import java.time.Instant;
@WebListener
public class AppStartupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("startedAt", Instant.now());
System.out.println("App started: " + event.getServletContext().getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
System.out.println("App stopped: " + event.getServletContext().getContextPath());
}
}
Output in the Tomcat terminal for a deploy, one request to /lifecycle, and an undeploy:
App started: /student-portal
ReportServlet ready in 801 ms on Catalina-utility-1
1. constructor thread=http-nio-8080-exec-1
2. init() thread=http-nio-8080-exec-1
3. doGet() #1 thread=http-nio-8080-exec-1
4. destroy() after 1 requests
App stopped: /student-portal
| Scope | Startup hook | Shutdown hook |
|---|---|---|
| One servlet | init() | destroy() |
| Whole web app | contextInitialized() | contextDestroyed() |
How it works:
@WebListenerregisters the class, just like@WebServletregisters a servlet.- Attributes stored on the
ServletContextare visible to every servlet:getServletContext().getAttribute("startedAt"). - The listener starts first and stops last, so resources it opens are available for the entire life of every servlet.
One Instance, Many Threads: Keeping Servlets Thread-Safe
Because one servlet object serves all requests at the same time, any instance field that a request changes is shared data. Unsafe fields lead to the lost updates described in Java Thread Safety.
@WebServlet("/counter")
public class CounterServlet extends HttpServlet {
private int unsafeCount = 0; // shared, not thread-safe
private final AtomicInteger safeCount = new AtomicInteger();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
unsafeCount++; // read-modify-write race
safeCount.incrementAndGet(); // atomic
response.getWriter().println(unsafeCount + " " + safeCount.get());
}
}
Send 2,000 requests at the same time with virtual threads:
// LoadTest.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.Executors;
public class LoadTest {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create("http://localhost:8080/student-portal/counter")).build();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 2000; i++) {
executor.submit(() -> client.send(request, HttpResponse.BodyHandlers.discarding()));
}
} // waits for all requests to finish
System.out.print("unsafe safe = ");
System.out.print(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
}
}
Output (the first number changes from run to run):
unsafe safe = 1987 2001
How it works:
unsafeCount++reads, adds and writes in three steps. When two threads do this at once, one update is lost, so the unsafe count ends below 2,001.AtomicInteger.incrementAndGet()does the same in one indivisible step, so it always reaches 2,001 (2,000 test requests plus the final one).- Local variables inside
doGetare safe, because each thread gets its own copy. Keep per-request data in local variables and treat fields as shared.
Note: Do not add
synchronizedtodoGetto fix this. It forces every request to wait in line and removes the benefit of the container's thread pool.
Handle a Failed init With UnavailableException
If a servlet cannot start, for example because a required file is missing, init() should throw an exception. UnavailableException lets you say whether the problem is permanent or temporary.
@WebServlet(urlPatterns = "/rates", loadOnStartup = 2)
public class RatesServlet extends HttpServlet {
@Override
public void init() throws ServletException {
try {
if (getServletContext().getResource("/WEB-INF/rates.csv") == null) {
// Temporary: tell clients to retry in 60 seconds
throw new UnavailableException("rates.csv not uploaded yet", 60);
}
} catch (MalformedURLException e) {
throw new ServletException("Bad resource path", e);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.getWriter().println("Rates loaded");
}
}
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/student-portal/rates
Output:
503
How it works:
- An exception from
init()means the servlet never enters service, anddestroy()is not called for it, because it was never initialized. - For a temporary
UnavailableException, the Servlet specification requires the container to answer503 Service Unavailable. The container triesinit()again later. new UnavailableException("message")without seconds marks the servlet permanently unavailable.
Real-World Example: Servlet Lifecycle in Java for a Cached Course Catalog
This servlet loads a course catalog from WEB-INF/courses.csv during init(), reloads it in the background every few minutes, serves requests from memory, and stops its background thread in destroy().
# src/main/webapp/WEB-INF/courses.csv
java,Java Tutorial,306
python,Python Tutorial,120
go,Go Language,90
package com.gocourse.portal;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
@WebServlet(
urlPatterns = "/catalog/*",
loadOnStartup = 1,
initParams = {
@WebInitParam(name = "catalogFile", value = "/WEB-INF/courses.csv"),
@WebInitParam(name = "refreshMinutes", value = "5")
})
public class CatalogServlet extends HttpServlet {
record Course(String code, String title, int lessons) {}
// volatile: request threads always see the latest map that the refresher published
private volatile Map<String, Course> catalog = Map.of();
private final AtomicLong requestsServed = new AtomicLong();
private ScheduledExecutorService refresher;
private String catalogFile;
@Override
public void init() throws ServletException {
catalogFile = getInitParameter("catalogFile");
long refreshMinutes = Long.parseLong(getInitParameter("refreshMinutes"));
reloadCatalog(); // fail deployment if the first load fails
log("Loaded " + catalog.size() + " courses from " + catalogFile);
refresher = Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, "catalog-refresher");
thread.setDaemon(true);
return thread;
});
refresher.scheduleAtFixedRate(() -> {
try {
reloadCatalog();
} catch (ServletException e) {
log("Refresh failed, keeping previous catalog", e);
}
}, refreshMinutes, refreshMinutes, TimeUnit.MINUTES);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
requestsServed.incrementAndGet();
Map<String, Course> snapshot = catalog; // read the field once per request
response.setContentType("text/plain;charset=UTF-8");
String pathInfo = request.getPathInfo(); // null or "/java"
if (pathInfo == null || pathInfo.equals("/")) {
snapshot.values().forEach(course ->
response.getWriter().println(course.code() + " - " + course.title()));
return;
}
Course course = snapshot.get(pathInfo.substring(1));
if (course == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown course");
return;
}
response.getWriter().println(course.title() + " has " + course.lessons() + " lessons");
}
@Override
public void destroy() {
if (refresher != null) {
refresher.shutdownNow(); // stop the background thread
}
log("Catalog servlet stopped after serving " + requestsServed.get() + " requests");
}
private void reloadCatalog() throws ServletException {
try (InputStream input = getServletContext().getResourceAsStream(catalogFile)) {
if (input == null) {
throw new ServletException("Catalog file not found: " + catalogFile);
}
Map<String, Course> fresh = new LinkedHashMap<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
if (line.isBlank() || line.startsWith("#")) continue;
String[] parts = line.split(",");
fresh.put(parts[0], new Course(parts[0], parts[1], Integer.parseInt(parts[2].trim())));
}
catalog = Collections.unmodifiableMap(fresh); // publish a read-only snapshot
} catch (IOException | RuntimeException e) {
throw new ServletException("Cannot load " + catalogFile, e);
}
}
}
Deploy, call it, then undeploy:
cp target/student-portal.war $CATALINA_HOME/webapps/
curl -s http://localhost:8080/student-portal/catalog
curl -s http://localhost:8080/student-portal/catalog/java
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/student-portal/catalog/rust
rm $CATALINA_HOME/webapps/student-portal.war
grep CatalogServlet $CATALINA_HOME/logs/localhost.*.log
Output:
java - Java Tutorial
python - Python Tutorial
go - Go Language
Java Tutorial has 306 lessons
404
... INFO [Catalina-utility-1] ... CatalogServlet: Loaded 3 courses from /WEB-INF/courses.csv
... INFO [Catalina-utility-2] ... CatalogServlet: Catalog servlet stopped after serving 3 requests
How it works:
- Startup work in
init().loadOnStartup = 1loads the catalog while the app deploys. If the file is missing,init()throws and the error appears in the deployment log, before users arrive. - Settings from init parameters. The file path and refresh interval come from
@WebInitParam, so operations staff can change them inweb.xmlwithout touching code. - Safe sharing between threads. The background thread builds a new map and publishes it with one write to a
volatilefield. Request threads read that field once and work with an immutable snapshot, so they never see a half-loaded catalog and need no locks. The map is never changed after it is published, so the read-only wrapper is safe to share. - Cleanup in
destroy().shutdownNow()stops the refresher thread. Without it, the thread would keep the old class loader alive after undeploy, causing a memory leak that Tomcat reports as "appears to have started a thread ... but has failed to stop it". - Container logging.
log(...)writes to the container's log (localhost.<date>.login Tomcat) with the servlet's name, which is easier to search thanSystem.out. The snapshot wraps aLinkedHashMap, so courses print in file order. Reading request data such asgetPathInfo()in more detail is the topic of HttpServletRequest in Java.