Servlet Lifecycle Overview
In this article, we will explore the complete lifecycle of a Servlet object in Java web applications. Understanding how Servlets are created, executed, and destroyed is fundamental to building robust web applications.
What is Servlet Lifecycle?
The Servlet lifecycle refers to the complete journey of a Servlet object from the moment it is created until it is destroyed. This includes:
- When the Servlet object is instentiated
- When initialization methods are called
- When service methods handle client requests
- When the Servlet is finally destroyed
Who Manages the Servlet Lifecycle?
Java web developers do not have direct control over the Servlet lifecycle. The web container (typically Apache Tomcat) is fully responsible for:
- Creating Servlet instances
- Calling appropriate methods on those instances
- Destroying Servlet objects when they are no longer needed
The web container maintains a collection (implemented as a HashMap internally) that associates request paths with their corresponding Servlet instances. Only Servlets managed by this collection are subject to container lifecycle management.
Servlet Instance Creation During Server Startup
By default, when the application server starts, Servlets are not instantiated immediately. They are created only when the first client request arrives.
This design is efficient because pre-instantiating all Servlets would consume unnecessary memory, especially for Servlets that might never be accessed by users.
Forcing Early Initialization
To create a Servlet when the server starts, add the load-on-startup element in the deployment descriptor:
<servlet>
<servlet-name>userServlet</servlet-name>
<servlet-class>com.example.web.UserServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>userServlet</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>
The integer value specifies startup priority. Lower numbers indicate higher priority.
The Complete Lifecycle Phases
Phase 1: First Request Arrival
When the first HTTP request is received, the container performs the following operations:
UserServlet constructor invoked
UserServlet initialization completed
UserServlet service method processing request
Key observations:
- The no-argument constructor executes once to instantiate the Servlet
- The
init()method executes immediately after construction - The
service()method is called to handle the request
Phase 2: Subesquent Requests
For the second, third, and all additional requests:
UserServlet service method processing request
Key observations:
- The constructor does not execute again
- The
init()method does not execute again - The same Servlet instance handles all requests (singleton pattern)
- The
service()method executes once per request
While Servlets appear to follow a singleton pattern, they are technically "pseudo-singletons" because the container controls instantiation entirely.
Phase 3: Server Shutdown
When the server is stopped:
UserServlet cleanup operations completed
The destroy() method executes once, allowing the Servlet to release resources such as database connections, file handles, or cached data.
Lifecycle Method Summary
| Method | Execution Count | Typical Use |
|---|---|---|
| Constructor | Once | Object creation (rarely customized) |
| init() | Once | One-time initialization (database connections, pools) |
| service() | Per request | Request handling |
| destroy() | Once | Resource cleanup |
Important Considerations
Avoid Custom Constructors
If you define a parameterized constructor without explicitly providing a no-argument constructor, instantiation will fail:
public class UserServlet implements Servlet {
public UserServlet(String configName) {
// This overrides the implicit no-argument constructor
}
}
Attempting to access this Servlet results in:
NoSuchMethodException: com.example.web.UserServlet.()
<p>Therefore, it is recommended to avoid defining custom constructors in Servlet classes. The <code>init()</code> method exists precisely for this purpose—it provides a dedicated initialization point that the container can invoke reliably.</p>
<h4>When to Use Each Method</h4>
- service(): Always required. This is where request processing occurs.
- init(): Use for expensive one-time setup operations like connection pool initialization.
- destroy(): Use for closing resources and saving state before the application shuts down.
Lifecycle Analogy
Consider the Servlet lifecycle as analogous to a person's career:
- Constructor: Birth—the Servlet comes into existence
- init(): Education—preparing for work
- service(): Employment—serving clients
- destroy(): Retirement—cleaning up before ending