Thread security issues with spring concurrent access

Source: Internet
Author: User

SPRINGMVC's controller is singleton (non-thread safe), which is probably the difference between him and struts2.
Like struts, Spring's controller defaults to Singleton, 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 don't have to create a controller every time, The second is to reduce the time of object creation and garbage collection; Since there is only one controller's instance, when multiple threads call it, the instance variable inside it is not thread-safe, and the problem of channeling data can occur.

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 extends Abstractcommandcontroller {  ...   protected Modelandview handle (httpservletrequest request,httpservletresponse response,              throws  Exception {  = ......... ;  }   protected Company company ;  }  

There is a tag company here that has a concurrency thread safety problem.
If the controller is in a singleton form, and there is a private variable A in it, all requests to the same controller, the A variable used is common, that is, if the variable A is modified in a request, the content of the modification can be read in the other request.

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.

"1" springmvc how to ensure the security of objects in multi-threaded environment?

The code is as follows:

@RequestMapping ("/user") @Controller Class usercontroller {@Resource userservice userservice; @RequestMapping ("/add")       Public voidTestA (user user) {userservice.add (user); } @RequestMapping ("/get")       Public voidTestA (intID)      {userservice.get (ID); }} @Service ("UserService") Class userservice{ Public StaticMap<integer,user> Userscache =NewHashmap<string,user>();  Public voidAdd (user user) {userscache.put (User.getid (), user); }         Public voidGetintID)      {userscache.get (ID); }    }

This fragment of code, the Userscache object is thread insecure. Because it is a static global shared object. If there are multiple threads calling the Add method at the same time, it may occur that the user object is overwritten, that is, the ID corresponds to the object inconsistency, which is the most common thing in multithreaded programming. Therefore, you can use the Collections tool to synchronize the map. Static Map<integer, users> Userscache = Collections.synchronizedmap (New Hashmap<integer, Users> ()); To study the source code in spring, it does a lot of encapsulation of common open source frameworks, such as sessionfactory in Hibernate, using Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean, while in In Annotationsessionfactorybean's parent class Localsessionfactorybean, a large number of threadlocal are defined to ensure the security of multithreading.
 Public classLocalsessionfactorybeanextendsAbstractsessionfactorybeanImplementsBeanclassloaderaware {Private Static FinalThreadlocal<datasource> Configtimedatasourceholder =NewThreadlocal<datasource>(); Private Static FinalThreadlocal<transactionmanager> Configtimetransactionmanagerholder =NewThreadlocal<transactionmanager>(); Private Static FinalThreadlocal<object> Configtimeregionfactoryholder =NewThreadlocal<object>(); Private Static FinalThreadlocal<cacheprovider> Configtimecacheproviderholder =NewThreadlocal<cacheprovider>(); Private Static FinalThreadlocal<lobhandler> Configtimelobhandlerholder =NewThreadlocal<lobhandler> ();

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.