Difference between each instance of servlet and each thread of servlet in servlets?

JavaServlets

Java Problem Overview


Are there multiple instances of servlet class? As I hear "each instance of servlet" Can anybody elaborate on this?

Java Solutions


Solution 1 - Java

When the Servlet container starts, it:

  1. reads web.xml;
  2. finds the declared Servlets in the classpath; and
  3. loads and instantiates each Servlet only once.

Roughly, like this:

String urlPattern = parseWebXmlAndRetrieveServletUrlPattern();
String servletClass = parseWebXmlAndRetrieveServletClass();
HttpServlet servlet = (HttpServlet) Class.forName(servletClass).newInstance();
servlet.init();
servlets.put(urlPattern, servlet); // Similar to a map interface.

Those Servlets are stored in memory and reused every time the request URL matches the Servlet's associated url-pattern. The servlet container then executes code similar to:

for (Entry<String, HttpServlet> entry : servlets.entrySet()) {
    String urlPattern = entry.getKey();
    HttpServlet servlet = entry.getValue();
    if (request.getRequestURL().matches(urlPattern)) {
        servlet.service(request, response);
        break;
    }
}
    

The GenericServlet#service() on its turn decides which of the doGet(), doPost(), etc.. to invoke based on HttpServletRequest#getMethod().

You see, the servletcontainer reuses the same servlet instance for every request. In other words: the servlets are shared among every request. That's why it's extremely important to write servlet code the threadsafe manner --which is actually simple: just do not assign request or session scoped data as servlet instance variables, but just as method local variables. E.g.

public class MyServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;
        
        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    } 
}

Solution 2 - Java

No, there is only one instance of the servlet which is reused for multiple requests from multiple clients. This leads to two important rules:

  • don't use instance variables in a servlet, except for application-wide values, most often obtained from context parameters.
  • don't make methods synchronized in a servlet

(same goes for servlet filters and jsps)

Solution 3 - Java

According to the Java Servlet Specification Version 3.0 (pp. 6-7), there will be one instance per declaration per JVM, unless the servlet implements SingleThreadModel in which case there may be multiple instances per JVM.

Solution 4 - Java

Although there are already a few good answers, none of them spoke about a Java web application deployed in a distributed environment. This is a practical scenario where actually multiple instances of a single servlet are created. In a distributed environment you have a cluster of machines to handle the request and the request can go to any of these machines. Each of these machines should be capable to handle the request and hence every machine should have an instance of your MyAwesomeServlet in it's JVM.

So, the correct statement would be there is only one instance per JVM for every servlet, unless it implements SingleThreadModel.

SingleThreadModel in simple words says that you have to have only one thread per instance of Servlet, so basically you need to create one instance per coming request to handle it, which basically kills the whole concept of handling requests in a parallel fashion and isn't considered a good practice as the servlet object creation and initialization takes up time before it's ready to process the request.

Solution 5 - Java

There can not be multiple instances of servlet class. Even when there is one instance of the servlet, it is able to handle multiple requests. So it is wise not to use class level variables.

Solution 6 - Java

For those that know real JavaScript (not just a library of it), Servlets can be viewed as function objects. As functional objects, the main task of them is to do something, instead of to store some information in their chests. There is no need to instantiate more than one instance of every such functional object, with the same rationale that Java class methods are shared among all instances of that class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongiriView Question on Stackoverflow
Solution 1 - JavaBalusCView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavaSamuel Edwin WardView Answer on Stackoverflow
Solution 4 - JavaSaurabh PatilView Answer on Stackoverflow
Solution 5 - JavafastcodejavaView Answer on Stackoverflow
Solution 6 - JavalcnView Answer on Stackoverflow