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 takes a thread out of the thread pool, locates the Servlet object for the request and initializes it, and then calls the service () method. 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.
Thread1 and Thread2 Call the same Servlet1, so if an instance variable or a static variable is defined in Servlet1, then 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.
Import Javax.servlet.Servletexception;Import Javax.servlet.http.HttpServlet;Import Javax.servlet.http.HttpServletRequest;Import Javax.servlet.http.HttpServletResponse;Import java.io.IOException;Import Java.text.SimpleDateFormat;Import Java.util.Date;publicClassThreadsafeservletExtendsHttpServlet {public staticString name ="Hello";Static variables, thread safety problems may occur int i;instance variables, thread safety issues may occurSimpleDateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd hh:mm:ss");@Override public void Init ()Throwsservletexception {Super.init ();System.out.println ("Servlet initialization"); }@Overrideprotected void Service (HttpServletRequest req,HttpServletResponse resp)ThrowsServletexception,ioexception {system.out.printf ( "%s:%s [%s]\n ", thread.currentthread (). GetName (), I, Format.format ( New date ())); i++; try {thread.sleep (5000);} catch (interruptedexception e) {e.printstacktrace ();} system.out.printf ("%s:%s[%s]\n ", Thread.CurrentThread (). GetName (), I, Format.format (new Date ()) ); 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.
The servlet is not thread-safe.