Thread security issues with Spring concurrent access

Source: Internet
Author: User


First of all, for the spring IOC, the object is managed by spring, that is, when spring starts, in the spring container, it is created by spring, and spring will help us maintain it, which is generally a singleton, that is, an object.


The spring generation object is singleton by default. You can change to multiple cases by using the scope property.


Part I: Verify that the spring generated object is a singleton by default.


Let's take a look at an online example to verify:

<bean id= "singleton" class= "Java.util.Date" scope= "singleton" ></bean><bean id= "prototype" class= " Java.util.Date "scope=" prototype "></bean>
Package test; Import Java.util.date;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.opensymphony.xwork2.ActionContext ;p Ublic class Testscope {public    static void Main (string[] args) {       ApplicationContext context=new Classpathxmlapplicationcontext ("Applicationcontext-web.xml");       Date s1= (date) Context.getbean ("Singleton");       Date p1= (date) Context.getbean ("Prototype");       Date s2= (date) Context.getbean ("Singleton");       Date p2= (date) Context.getbean ("Prototype");           SYSTEM.OUT.PRINTLN ("single Case:" + (S1==S2));       SYSTEM.OUT.PRINTLN ("Non-Singleton:" + (P1==P2));}    }

Output Result:

Results

Single case: True

Non-singleton: false


Note: the "= =" of the composite data type " compared to the address stored in memory, so here we use "= =" to compare

because Object in the equals The initial behavior is to compare addresses in memory, but is overwritten in some class libraries such as ( String , Integer , Date , etc.)


The second part:Springmvc and Struts2 is a thread safety issue in the presence of concurrent access No.


For people who have used SPRINGMVC and Struts2, we all know that SPRINGMVC is based on method interception, and Struts2 is class-based interception.


for Struts2, struts instantiates an object each time a request is processed, so that there is no thread-safe problem ;

Spring's controller is singleton by default, which means that every request comes in and the system is processed with the original instance, which results in two outcomes:

One is that we do not have to create a controller each time, the second is to reduce the creation of objects and garbage collection time; because there is only one controller instance, when multiple threads call it, the instance variable inside it is not thread-safe, it will occur the problem of channeling data.


Of course, in most cases, we do not need to consider thread-safety issues, such as Dao,service, unless you declare an instance variable in the bean. Therefore, when we use Spring MVC's contrller, we should avoid defining instance variables in the controller.
Such as:

public class Controller extends Abstractcommandcontroller {      protected company Company;    Protected Modelandview handle (httpservletrequest request,httpservletresponse response,object command,bindexception Errors) throws Exception {company = .........}            }  

Solution:

There are several workarounds:
1. Use the threadlocal variable in the controller
2. Declare scope= "prototype" in the Spring Config file controller and create a new controller each time
When you use spring to develop the web, be aware that the default controller, Dao, and service are all singleton.


For example:

@Controller @requestmapping ("/fui") public class Fuicontroller extends Springcontroller {// This definition is a singleton @controller@scope ("prototype") @RequestMapping ("/fui") public class Fuicontroller extends Springcontroller {//Create each time


the third part:the difference between SPRINGMVC and Struts2 .


Here is a comparison from the network excerpt, you can see

Click to open link


1. Mechanism: Spring MVC's entry is the servlet, and Struts2 is the filter, which results in a different mechanism.


2. Performance: Spring will be slightly faster than struts. Spring MVC is a method-based design, and Sturts is class-based, each time a request is made with an action, each action is injected into the attribute, and spring is based on a method that is finer grained, but be careful to hold the same data as the servlet. SPRING3 MVC is a method-level interception that, after intercepting a method, injects the request data into a parameter based on annotations, and in Spring3 MVC, a method corresponds to a request context. The STRUTS2 framework is a class-level intercept, creating an action every time a request is made, and then invoking the setter getter method to inject the data from the request; Struts2 actually deals with the request through the setter getter method. ; in Struts2, an Action object corresponds to a request context.


3. Parameter passing: Struts is a parameter that can be accepted with attributes when it is accepted, which means that the parameters are shared by multiple methods.


4. Design thinking: Struts more in line with OOP programming ideas, Spring is more cautious, extended on the servlet.


5. Intercepter implementation mechanism: Struts has its own interceptor mechanism, and spring MVC uses an independent AOP approach. This leads to the profile of struts is still larger than spring MVC, although the configuration of struts can inherit, so I think in terms of use, Spring MVC use more concise, development efficiency Spring MVC is really higher than struts2. Spring MVC is a method-level intercept, a method that corresponds to a request context, and a method that corresponds to a URL, so it is easy to implement a restful URL spring3 mvc from the schema itself. STRUTS2 is class-level interception, a class corresponds to a request context, and implementing a restful URL is laborious because a method of struts2 action can correspond to a URL, and its class properties are shared by all methods. It is also not possible to identify the method that it belongs to by annotations or other means. Spring3 MVC method is basically independent, the request response data, requests data through parameters, processing results through the MODELMAP to the framework method is not shared between the variables, and struts2 make is more chaotic, although the method is also independent, But all of its action variables are shared, which does not affect the program's operation, but it gives us code and trouble reading the program.


6. In addition, SPRING3 MVC validation is also a bright spot, support JSR303, processing AJAX Requests is more convenient, just a note @responsebody, and then directly return the response text.


Summarize:


This also shows that SPRINGMVC and Servlets are thread-safe methods, so the private or public variables declared in the class method are not thread-safe, and struts2 is indeed thread-safe.


Part IV:so what about struts2+spring to manage injections?

Struts2 It is a multi-instance, for each request will generate 1 instances, spring by default is single-instance (below for struts and spring integration of two ways to introduce the two struts2 and spring integration method)

One: For the integration of no spring plug-in (Struts2-spring-plugin-xxx.jar), you need to add the business logic controller class to the spring action Bean with scope= "prototype".

<bean id= "user" class= "modle. User "scope=" prototype "></bean>

Two : for the integration of spring plug-ins (Struts2-spring-plugin-xxx.jar): Anti-compilation strutsspringobjectfactory and related code only found if the struts Action in the configuration file <action name= ":" class= "..." /> in class if the full package name and class name is the struts create action object, that is, multi-instance;


Summary: If the name of the bean in the spring configuration file is spring creation, then the single instance or multi-instance is configured by the business logic controller class in spring's action bean to scope= "prototype", which is a multi-instance, There is no single instance, the order is first found in spring, not found again from the struts configuration file.





Thread security issues with Spring concurrent access

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.