Servlets
instantiation
sessions
shared variables
multithreading

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.

Browse interview questions

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:

  1. 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.
  2. 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. The init() method is called once in the servlet's lifecycle.
  3. Request Handling: The servlet responds to user requests by invoking its service() method. For HTTP servlets, which subclass HttpServlet, this method dispatches the request to specialized methods like doGet(), doPost(), etc., based on the HTTP request type.
  4. 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.
java
1public class ExampleServlet extends HttpServlet {
2    public void init() throws ServletException {
3        // Initialization code here
4    }
5  
6    public void doGet(HttpServletRequest request, HttpServletResponse response)
7        throws ServletException, IOException {
8        // Request handling code here
9    }
10
11    public void destroy() {
12        // Cleanup code here
13    }
14}

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 HttpSession object. 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) and getAttribute(String name).
java
1HttpSession session = request.getSession();
2session.setAttribute("username", "JohnDoe");
3
4String username = (String) session.getAttribute("username");

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 ServletContext for data that needs to be shared across requests and servlets. Note that access to ServletContext attributes should be controlled to prevent stale data or synchronization issues.
java
synchronized(this) {
    // Critical section
}

Multithreading in Servlets

Concurrent Request Handling

  • Single-Thread Model: The deprecated SingleThreadModel interface was used to provide thread safety but resulted in scalability issues. Instead, modern containers handle multiple requests by multithreading the calls to the servlet's service() 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.concurrent package, such as ConcurrentHashMap.

Summary Table

AspectDescriptionExample/Note
InstantiationServlets are loaded once and instantiated once by the container.init(), new ExampleServlet()
Session HandlingUses HttpSession for tracking user data across requests.request.getSession()
Shared VariablesAvoid using instance variables; prefer local to maintain thread safety.synchronized(this)
MultithreadingManage concurrent requests with a thread pool.Use of service() method
Thread SafetyLeverage 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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.