Are there multiple instances of servlet class? As I hear "each instance of servlet" Can anybody elaborate on this?
Usually, there is only one instance of a specific servlet in the container. This servlet gets reused for every request. However, by default, every servlet request runs in a different thread.
So, the correct statement would be there is only one instance per JVM for every servlet, unless it implements SingleThreadModel.
2) Servlet instance is createdThe web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.
So in you case too, instance variable are not thread safe, because if two thread access the same instance they can disturb each other.
When the Servlet container starts, it:
web.xml
;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. } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With