Before talking about struts2's thread safety, let me first talk about what is thread safety? This is what a netizen said.
If your code is in the process where you are in, there are multiple threads running at the same time, and these threads may run this code at the same time. If the result of each run is the same as the result of a single thread run, and the values of other variables are the same as expected, it is thread-safe.
That is to say, in a process, multiple threads execute concurrently. During each thread's execution, the variable values are the same and the execution results are the same, which is thread-safe. Otherwise, the thread is unsafe.
Then review the thread safety issues of servlets. Since servlets are singleton mode, only one instance will be generated. When multiple users request a servlet at the same time, Tomcat will derive multiple threads to execute the servlet code. Therefore, servlets are thread-safe. If used improperly, problems may occur. Here is 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;public class ThreadSafeServlet extends HttpServlet { private String name;//Define a public private variable name public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //Get name attribute from the request field name =request.getParameter("name"); //Let the thread sleep for 10 seconds try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } //Output name value to the browser response.getWriter().print("name="+name); }}We use two browsers to access ThreadSafeServlet?name="zhangSan" and ThreadSafeServlet?name="liSi" within ten seconds. The results are both name=liSi, which means that there is a problem with the program. Multi-thread concurrent reading and writing will lead to data out of synchronization. Therefore, when using servlets, we try not to define global private attributes, but define variables into doGet() and doPost() methods respectively. Of course, if it is just a read operation, there will be no problem. Therefore, if you want to define global read-only attributes in servlets, it is best to define the final type.
Action in Struts2 creates an instance for each request. There is no difference between Action and ordinary Java classes, and there will be no data out of sync, so it is thread-safe.
The above is all about this article, I hope it will be helpful to everyone's learning.