Transferred from: http://www.cnblogs.com/chanshuyi/p/5052426.html
The servlet is not thread-safe.
To explain why a servlet is not thread-safe, you need to understand how the servlet container (that is, Tomcat) responds to HTTP requests.
When Tomcat receives an HTTP request from the client, tomcat extracts a thread from the thread pool and then finds the Servlet object for that request. If the servlet has not been requested yet, the servlet initializes and invokes the servlet and invokes the service () method. Otherwise, call the service () method directly. Note that there is only one instance object in each Servlet object in the Tomcat container, which is a singleton pattern. If multiple HTTP requests request the same servlet, then the corresponding thread for the two HTTP requests will call the servlet's service () method concurrently.
At this point, if an instance variable or a static variable is defined in the servlet, a thread-safety problem may occur (because all threads may use these variables).
For example, the following servlet name
and i
variables will cause thread safety issues.
Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.IOException;ImportJava.text.SimpleDateFormat;Importjava.util.Date; Public classThreadsafeservletextendsHttpServlet { Public StaticString name = "Hello";//static variables, thread safety issues may occur intI//instance variables, thread safety issues may occurSimpleDateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"); @Override Public voidInit ()throwsservletexception {Super. Init (); System.out.println ("Servlet initialization"); } @Overrideprotected voidService (HttpServletRequest req, HttpServletResponse resp)throwsservletexception, IOException {System.out.printf ("%s:%s[%s]\n", Thread.CurrentThread (). GetName (), I, Format.format (NewDate ())); I++; Try{Thread.Sleep (5000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.printf ("%s:%s[%s]\n", Thread.CurrentThread (). GetName (), I, Format.format (NewDate ())); Resp.getwriter (). println ("); }}
Launching this servlet in Tomcat and initiating multiple HTTP accesses in the browser will eventually reveal that i
the variables are shared in multi-threaded.
If you need more in-depth understanding of the details of Tomcat receiving HTTP and the details of interacting with the servlet, you can take a closer look at Tomcat architecture and source code.
Resources:
1, http://www.ibm.com/developerworks/cn/java/j-lo-tomcat1/
2, http://blog.csdn.net/cutesource/article/details/5040417
Java interview question: is the servlet thread-safe?