Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Describe the servlet lifecycle. How many instances of a servlet exist, and what does that mean for instance fields?

The container loads the servlet class, creates one instance per servlet declaration and calls init(ServletConfig) once; it then calls service() for every request, which dispatches to doGet, doPost and the other methods, and calls destroy() once at shutdown. Because that single instance serves many requests on many threads at the same time, mutable instance fields are shared and not thread-safe. load-on-startup makes the container create and initialise the servlet when the application starts instead of at the first request.

Why this question is asked

Even in Spring Boot applications where we never write a servlet by hand, everything runs on top of the servlet lifecycle: Spring MVC's DispatcherServlet is a servlet, and the threading rule that applies to servlets applies to every singleton bean behind it. Interviewers ask this question because the instance count and its consequence for fields catch a real class of production bugs. In this answer, we will recap what a servlet and a container are, walk through the three lifecycle phases, look at how many instances exist, reproduce the instance field bug and fix it, and see what load-on-startup changes.

1A Quick Recap of Servlets and Containers

A servlet is a Java class that handles HTTP requests. It extends HttpServlet from the jakarta.servlet.http package (javax.servlet before Jakarta EE 9) and overrides methods such as doGet or doPost. A servlet container, such as Tomcat, Jetty or Undertow, is the server that listens for HTTP connections, turns each request into HttpServletRequest and HttpServletResponse objects, and calls the right servlet.

We do not create servlets with new. The container creates them and decides when to call each of their methods. That sequence of calls is the servlet lifecycle.

2The Three Phases of the Lifecycle

First, loading and initialisation. The container loads the servlet class, creates an instance with the no-argument constructor, and calls init(ServletConfig config) exactly once. ServletConfig gives the servlet its name, its init parameters and access to the ServletContext, the object that represents the whole web application. HttpServlet's parent, GenericServlet, stores the config and then calls the no-argument init(), which is the method we normally override to open resources or read configuration.

Second, request handling. For every request mapped to the servlet, the container calls service(ServletRequest, ServletResponse). HttpServlet's implementation looks at the HTTP method and dispatches to doGet, doPost, doPut, doDelete and so on. A method we do not override answers with 405 Method Not Allowed.

Third, destruction. When the application is stopped or undeployed, the container waits for running requests to finish, up to a grace period, and then calls destroy() once. That is where we release what init() acquired. After destroy(), the instance is never used again.

Java
@WebServlet(urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override public void init() { log("init"); } // once, before the first request
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("hello"); // for every GET /hello
}
@Override public void destroy() { log("destroy"); } // once, at shutdown
}
// log: init, then many requests, then destroy
Step throughThe servlet lifecycle
  1. Container loads the classat startup if load-on-startup, else at the first request
  2. Create one instanceno-argument constructor
  3. init(ServletConfig)once; open resources here
  4. service() for each requestdispatches to doGet, doPost, ...; many threads at once
  5. destroy()once, at shutdown; release resources

5 steps in order. Play them, or step through them one at a time.

3How Many Instances Exist?

The container creates one instance per servlet declaration, per running application. A declaration is one @WebServlet annotation, one servlet entry in web.xml, or one registration through the ServletContext or a Spring Boot ServletRegistrationBean. If we declared the same class twice under two names, there would be two instances, each with its own config, but a normal application has one instance of each servlet.

That one instance handles every request to its URLs. The container keeps a pool of worker threads, 200 by default in Tomcat, and each incoming request runs on one of those threads. So when 50 requests arrive at once, 50 threads call service() on the same object at the same time. The old SingleThreadModel interface, which promised one thread per instance, was deprecated long ago and has been removed from the current Servlet specification.

4Why Mutable Instance Fields Are Not Thread-Safe

Since all those threads share one object, they share its fields. A field that is only read, such as a configuration value set in init(), is fine. A field that requests change is a race condition. Here is a servlet that counts its hits in a plain int field.

Java
public class HitServlet extends HttpServlet {
private int hits; // shared by every request thread
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
hits++; // read, add, write: three steps, not atomic
resp.getWriter().println(hits);
}
}
// 1,000 concurrent GETs -> final value often below 1000, for example 987

hits++ reads the value, adds one and writes it back. When two threads read the same value, say 41, both write 42, and one hit is lost. Worse examples are a field holding the current user or a SimpleDateFormat, which is not thread-safe, so one request can see another user's data or a corrupted date. The fix is to keep per-request state in local variables or request attributes, and make shared state thread-safe.

5Fixing It and Keeping State in the Right Place

For a shared counter, an AtomicInteger performs the increment as one atomic operation. For per-request data, local variables are naturally safe because each thread has its own stack.

Java
public class HitServlet extends HttpServlet {
private final AtomicInteger hits = new AtomicInteger(); // thread-safe shared counter
private final DateTimeFormatter fmt = DateTimeFormatter.ISO_LOCAL_DATE; // immutable, safe to share
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String user = req.getRemoteUser(); // local: belongs to this request only
int n = hits.incrementAndGet();
resp.getWriter().println(n + " " + LocalDate.now().format(fmt) + " " + user);
}
}
// 1,000 concurrent GETs -> final value 1000

The same rule applies to Spring. Controllers and services are singletons by default, called by many request threads at once, so they should be stateless or hold only thread-safe, effectively immutable fields.

6What load-on-startup Changes

By default, many containers create and initialise a servlet lazily, when the first request for it arrives, so that first user pays for init(). Setting load-on-startup to zero or a positive number, in web.xml or as loadOnStartup in @WebServlet, tells the container to initialise the servlet while the application starts. Lower numbers start first. That moves slow initialisation out of the first request and makes configuration errors fail the deployment immediately instead of hours later.

Java
@WebServlet(urlPatterns = "/report", loadOnStartup = 1) // init() runs during application startup
public class ReportServlet extends HttpServlet { /* ... */ }

7Follow-up questions

Can a servlet have a constructor with arguments?

No. The container creates servlets with the public no-argument constructor, so configuration comes through init parameters in ServletConfig, context parameters in ServletContext, or, in Spring Boot, through a ServletRegistrationBean that is given an instance we built ourselves, which can then have a constructor with dependencies.

What happens if init() throws an exception?

If init() throws a ServletException, the container does not put the servlet into service and requests to it fail, typically with an error status. With load-on-startup the failure shows up at deployment. destroy() is not called for a servlet whose init() failed.

Is the service method called on a new thread for every request?

It is called on a worker thread from the container's pool, so threads are reused across requests rather than created each time. That reuse is why thread-local data, such as logging MDC values, must be cleared at the end of each request.

8Conclusion

In this answer, we saw that the container loads a servlet class, creates one instance per servlet declaration, calls init(ServletConfig) once, calls service() for each request, which dispatches to doGet, doPost and the other methods, and calls destroy() once at shutdown. Because one instance serves many threads concurrently, mutable instance fields are shared and race, so per-request state belongs in local variables and shared state must be thread-safe. load-on-startup moves initialisation from the first request to application startup.

What to say in the interviewAbout 100 seconds aloud

Open with

The container manages the servlet's whole life. It loads the class and creates one instance per servlet declaration, so normally one instance per servlet in the application, using the no-argument constructor.

Then, if they want more

Then it calls init with the ServletConfig exactly once; that is where I would open resources or read init parameters.

After that, for every request mapped to the servlet, the container calls service on a worker thread, and HttpServlet's service looks at the HTTP method and dispatches to doGet, doPost, doPut and so on, returning 405 for methods I did not implement.

When the application shuts down, the container lets running requests finish and calls destroy once, where I release resources. The important consequence is threading. That single instance handles all requests concurrently, with Tomcat using a pool of up to 200 threads by default, so any mutable instance field is shared by all of them.

A plain int counter incremented in doGet loses updates, and a field holding the current user can leak one user's data to another. So I keep per-request data in local variables or request attributes, and shared state must be immutable or thread-safe, for example an AtomicInteger or a DateTimeFormatter instead of SimpleDateFormat.

The same rule applies to Spring singleton controllers and services. Finally, load-on-startup with a value of zero or more makes the container initialise the servlet at application startup instead of on the first request, so the first user does not pay for init and configuration errors fail the deployment early.

About this answer

Last updated
12 November 2026
Versions it names
Jakarta EE 9
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Describe the servlet lifecycle. How many instances of a servlet exist, and what does...": https://scrivio-interview-library.netlify.app/java/servlets/3deb77f018/