Servlets
Web Development
Java Programming
Multithreading
Session Management

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 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:

  1. Loading and Instantiation: The container loads the servlet class and creates an instance of the servlet by invoking its no-argument constructor.
  2. 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.
  3. 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.
  4. 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 HttpServletRequest object via the getSession() method, which returns a HttpSession object.

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 synchronized blocks 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:

java
1public class ThreadSafeCounterServlet extends HttpServlet {
2    private final AtomicInteger counter = new AtomicInteger(0); // Thread-safe integer
3
4    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
5        response.setContentType("text/plain");
6        int currentCount = counter.incrementAndGet(); // Atomically increments by 1
7        response.getWriter().println("Counter value: " + currentCount);
8    }
9}

Summary Table

AspectDescription
InstantiationManaged by servlet container, involves creating servlet instance and calling init()
SessionsManaged through the HttpSession object to store user data across multiple requests
Shared VariablesMust be accessed carefully in servlets to handle synchronization and ensure thread safety
MultithreadingServlets 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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the 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.