How do servlets work? Instantiation, sessions, shared variables and multithreading
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Servlets are Java programs that run on a server and handle requests and responses in a web application. They extend the capabilities of servers that host applications accessed by means of a request-response programming model. Understanding how servlets work involves exploring several core areas: instantiation, sessions, shared variables, and multithreading.
Instantiation and the Servlet Lifecycle
Servlet instantiation is part of the lifecycle managed by the Servlet container (such as Apache Tomcat, Jetty, or any Java EE web server). Here’s how the lifecycle is managed:
- Loading and Instantiation: The container loads the servlet class and creates an instance of the servlet by invoking its no-argument constructor.
- Initialization: The
init()method is called by the servlet container. This method is designed for any startup configuration or initialization code needed by the servlet. - Request Handling: For every client request, the servlet container will route the request to a thread, which calls the service method (i.e.,
doGet(),doPost()) of the servlet. This method will execute business logic and produce a response sent back to the client. - Destruction: When a servlet is no longer needed, the servlet container calls its
destroy()method. This is where cleanup code or resource release routines are typically placed.
Sessions
HTTP is a stateless protocol, which means each request-response pair is independent of others. Sessions provide a way to persist data across multiple HTTP requests. A session is created and managed as follows:
- A unique session ID is generated when a session is created.
- This ID is typically stored in a cookie on the client browser, which sends it with subsequent requests.
- The servlet accesses session information through the
HttpServletRequestobject via thegetSession()method, which returns aHttpSessionobject.
Using sessions, servlets can keep track of user-specific data such as login credentials, shopping cart items, and user preferences.
Shared Variables and Thread Safety
Servlets are inherently multi-threaded, as the servlet container typically creates a separate thread for each request. Shared resources or variables (defined as instance or static variables in servlets) must be handled carefully to avoid thread interference or memory consistency errors.
- Instance Variables: If servlets use instance variables, each servlet could modify these variables causing inconsistent data states in a multithreaded environment.
- Static Variables: Static variables are shared among all instances of the servlet class. If multiple threads access these static fields, synchronization mechanisms should be employed (using
synchronizedblocks or other concurrency controls in Java).
Multithreading
The multithreaded nature of servlets enables handling multiple requests simultaneously, enhancing performance. But it also introduces challenges related to shared resources:
- Concurrency Control: Proper synchronization is critical when multiple threads read and write shared variables.
- Pool of Servlet Instances: Some servlet containers might opt to maintain a pool of servlet instances and rotate their use among incoming requests to reduce instantiation overhead.
Here's an example to manage a shared counter with thread safety in a servlet:
Summary Table
| Aspect | Description |
| Instantiation | Managed by servlet container, involves creating servlet instance and calling init() |
| Sessions | Managed through the HttpSession object to store user data across multiple requests |
| Shared Variables | Must be accessed carefully in servlets to handle synchronization and ensure thread safety |
| Multithreading | Servlets handle multiple requests using threads, necessitating careful design especially around shared resources |
Conclusion
Understanding how servlets work is fundamental for developing robust Java web applications. By managing the servlet lifecycle, ensuring proper session management, and handling multithreading cautiously, developers can build efficient, secure, and scalable applications.
Related reading
- How do servlets work? Instantiation, sessions, shared variables and multithreading
- How do synchronized static methods work in Java and can I use it for loading Hibernate entities?
- How do synchronized static methods work in Java and can I use it for loading Hibernate entities?
- How do threads work in Python, and what are common Python-threading specific pitfalls?
- How do we count rows using older versions of Hibernate 2009?
- How do we define kafka request.timeout.ms property in spring kafka properties file
- How do two or more threads share memory on the heap that they have allocated?
- How do we use runOnUiThread in Android?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.