The Servlet Lifecycle
The Servlet Lifecycle
Servlets are not created fresh for every request. The container manages a pool of servlet instances and controls their entire lifecycle from creation to destruction.
Three Key Phases
The lifecycle has three distinct phases: initialization, service, and destruction.
Initialization: When the container starts (or when the first request arrives, depending on configuration), it loads the servlet class, creates a single instance, and calls init(). This happens exactly once per servlet.
@Override
public void init() throws ServletException {
// One-time setup: load config, open resources
String dbUrl = getServletConfig().getInitParameter("dbUrl");
this.dataSource = DataSourceFactory.create(dbUrl);
}
Service: For every incoming request, the container calls service(). The default service() method in HttpServlet inspects the HTTP method and dispatches to doGet, doPost, doPut, or doDelete.
Destruction: When the container shuts down, it calls destroy(). This is your chance to release resources - close database connections, stop background threads, flush caches.
@Override
public void destroy() {
// Clean up resources
if (dataSource != null) {
dataSource.close();
}
}
Threading Model
The container creates ONE instance of each servlet but handles concurrent requests by spawning threads. This means your servlet code must be thread-safe. Avoid mutable instance variables unless you synchronize access to them.
load-on-startup
By default, servlets are lazy-loaded on the first request. Set load-on-startup to a positive integer to make the container initialize them eagerly at deploy time:
<servlet>
<servlet-name>init</servlet-name>
<servlet-class>com.example.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Lower numbers load first. This is useful for servlets that warm up caches or validate configuration on startup.
Key Points
init()runs once when the servlet is first created.service()dispatches todoGet/doPost/doPut/doDeletefor each request.destroy()runs once when the container shuts down.- One servlet instance serves many threads - code must be thread-safe.
- Use
load-on-startupto initialize critical servlets eagerly.