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 a key component of Java web applications, allowing developers to build dynamic web pages and manage user requests. They run on a server in response to requests from clients, typically web browsers. In this article, we will explore how servlets work, with a focus on instantiation, sessions, shared variables, and multithreading.
Instantiation of Servlets
Lifecycle of a Servlet
A servlet's lifecycle is managed by the servlet container, which is part of a web server or application server. The lifecycle typically includes the following stages:
- Loading and Instantiation: When a servlet is requested for the first time, the servlet container loads the servlet class and creates a single instance of the servlet. The instantiation is done using the no-argument constructor.
- Initialization: Immediately after instantiation, the container calls the
init()method. This method is used to perform initialization tasks, such as setting up resources like database connections. Theinit()method is called once in the servlet's lifecycle. - Request Handling: The servlet responds to user requests by invoking its
service()method. For HTTP servlets, which subclassHttpServlet, this method dispatches the request to specialized methods likedoGet(),doPost(), etc., based on the HTTP request type. - Destruction: When the servlet is no longer needed, the container calls the
destroy()method to perform cleanup operations, such as releasing resources like file handles or database connections. After this, the servlet's instance is eligible for garbage collection.
Thread Safety and Instantiation
Since servlets are loaded once and instantiated once, it's crucial to ensure thread safety in the code. A servlet must be able to handle concurrent requests, which are served on multiple threads from a thread pool managed by the container.
Handling Sessions
Session Tracking
Servlets use sessions to maintain state across multiple requests from the same client. This is useful for activities like online shopping carts where data needs to be retained between different pages.
- Session Creation: When a new client accesses a servlet, the container creates an
HttpSessionobject. This can be done manually or automatically, depending on the application configuration. - Session ID: The session is tracked using a unique session ID, which is typically stored as a cookie on the client side. If cookies are disabled, URL rewriting can be utilized.
- Storing and Retrieving Data: You can store and retrieve data using the session object's methods:
setAttribute(String name, Object value)andgetAttribute(String name).
Shared Variables and Multithreading
Thread Safety Concerns
Shared variables in servlets, such as instance variables, pose a risk of data inconsistency and corruption due to concurrent access by multiple threads. There are several strategies to manage this:
- Avoid Instance Variables: Prefer using local variables within request-handling methods, as they are thread-safe by default.
- Synchronized Blocks: Use synchronized blocks or methods cautiously to control access to critical sections.
- ServletContext for Shared Data: Use
ServletContextfor data that needs to be shared across requests and servlets. Note that access toServletContextattributes should be controlled to prevent stale data or synchronization issues.
Multithreading in Servlets
Concurrent Request Handling
- Single-Thread Model: The deprecated
SingleThreadModelinterface was used to provide thread safety but resulted in scalability issues. Instead, modern containers handle multiple requests by multithreading the calls to the servlet'sservice()method. - Pooled Threads: Servlets use a pool of threads to handle incoming requests concurrently, improving efficiency and responsiveness.
Best Practices for Thread Safety
- Use local variables in methods to avoid shared state.
- Minimize the amount of logic inside synchronized blocks to reduce contention.
- Consider using concurrent utilities from the
java.util.concurrentpackage, such asConcurrentHashMap.
Summary Table
| Aspect | Description | Example/Note |
| Instantiation | Servlets are loaded once and instantiated once by the container. | init(), new ExampleServlet() |
| Session Handling | Uses HttpSession for tracking user data across requests. | request.getSession() |
| Shared Variables | Avoid using instance variables; prefer local to maintain thread safety. | synchronized(this) |
| Multithreading | Manage concurrent requests with a thread pool. | Use of service() method |
| Thread Safety | Leverage java.util.concurrent for complex synchronization needs. | ConcurrentHashMap |
Understanding these core concepts will allow developers to effectively leverage servlets for building robust, scalable web applications. When working with servlets, always keep in mind the implications of concurrent access and session management to ensure efficient processing and data integrity.
Related reading
- 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 two or more threads share memory on the heap that they have allocated?
- How do we use runOnUiThread in Android?
- How do you correctly await multiple asynchronous methods in dart?
- How do you create a daemon in Python?
- How do you create custom asynchronous functions in node.js?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free 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.