mvc framework thread safety problem

SpringMVC is method-based interception, and Struts2 is class-based interception. 
Every time Struts2 processes a request, an Action object will be instantiated, so there will be no thread safety issues. 
The controller of SpringMVC is singleton by default. 
The benefits of singletons:

  1. No need to create controller every time
  2. Reduce object creation time and garbage collection time.

It means that each request, the system will use the original instance to process, which will lead to multi-threaded calls, the instance variables in it are not thread-safe. 
However, in most cases we don't need to consider thread safety issues at all, such as dao, service, unless the instance variable declared in the bean. Therefore, the controller we use SpringMVC should avoid defining instance variables in the controller. 
Solution
1. When using the controller, avoid defining member variables in the controller. 
2. Change the scope of the controller to @Scope=”prototype”. 
3. Use ThreadLocal variables in the controller.

Question: Then the member variables in our business objects, such as xxxDao in Dao, or xxxService in controller, will be shared by multiple threads, so these objects will not have synchronization problems, such as database insertion and update. abnormal? 
Answer: These objects are indeed singletons, and there will be problems with thread synchronization. Although these objects will be accessed by multiple threads and cause concurrency problems, we actually access their methods. These classes usually do not contain member variables. The injected xxxDao is encapsulated by the Mybatis framework and has been tested, and there will be no thread synchronization problems. . So the problem is the business objects in our own system, so we must pay attention to these business objects must not have independent member variables, otherwise there will be errors.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326372758&siteId=291194637