Sobes.tech
Junior — Middle

How is Servlet processing performed in multi-threaded conditions?

sobes.tech AI

Answer from AI

In a Java Servlet container, usually one instance of a servlet is created and it handles multiple requests simultaneously using multiple threads. This means that the service() method (or doGet(), doPost(), etc.) is called concurrently in different threads.

Therefore, the servlet must be thread-safe. To achieve this:

  • Do not use instance fields to store request data or state, as they will be shared among all threads.
  • Use local variables within methods, which are safe in a multithreaded environment.
  • If you need to store state, use synchronization or thread-safe data structures.

If the servlet is not thread-safe, race conditions and incorrect behavior may occur.

Example of bad practice:

public class MyServlet extends HttpServlet {
    private int counter = 0; // shared among all threads

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        counter++; // not synchronized
        resp.getWriter().write("Counter: " + counter);
    }
}

It is better to use local variables or synchronization.

How is Servlet processing performed in multi-threaded… - sobes.tech