Before talking about the thread safety of struts2, what is thread-safe? This is a netizen speaking.
If you have more than one thread running at the same time in the process where your code is located, these threads may run the code at the same time. If the result of each run is the same as that of a single-threaded operation, and the value of other variables is the same as expected, it is thread-safe.
That is, there are multiple threads executing concurrently in a process, and the variable values are the same in each thread execution, and the execution result is the same, thread-safe. Otherwise, the thread is unsafe.
Then review the thread-safety issues of the servlet, because the servlet is a singleton pattern that only produces one instance, and when multiple users request a servlet at the same time, Tomcat derives multiple threads to execute the servlet's code. Therefore, the servlet is thread-unsafe and may cause problems if used improperly. Here's an example:
package com.wang.servlet;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; The public class Threadsafeservlet extends HttpServlet {Private String name;//defines a common private variable, the name of the publicly void Doget (Httpser Vletrequest request, HttpServletResponse response) throws Servletexception, IOException {response.setcontentty
PE ("text/html");
Gets the Name property name =request.getparameter ("name") from the Request field;
Causes the thread to hibernate 10 seconds try {Thread.Sleep (10000);
catch (Interruptedexception e) {e.printstacktrace ();
///Output value Response.getwriter (). Print ("Name=" +name) to the browser; }
}
We accessed the threadsafeservlet?name= "Zhangsan" and Threadsafeservlet?name= "LiSi" in 10 seconds, respectively, with two browsers, indicating that the results were name=lisi, which meant that there was a problem with the program, Multithreading concurrent read and write can cause data synchronization problem, so we use the servlet as far as possible not to define the global private properties, but the variables are defined into the doget () and Dopost () method, of course, if only read operation, there will be no problem, Therefore, if you want to define a global read-only property in the servlet, it is best defined as the final type.
The action in Struts2 creates an instance for each request, and the action is not any different from the normal Java class, and the data is not synchronized, so it is thread-safe.
The above is the entire content of this article, I hope to help you learn.