One, spring singleton mode and thread safety
The bean in the spring framework, or the component, is the default singleton mode when it comes to getting instances, which is especially important in the case of multithreaded development.
The singleton pattern means that there is only one instance. The singleton pattern ensures that a class has only one instance, and instantiates itself and provides this instance to the system as a whole. This class is called a singleton class. When multiple users request a service at the same time, the container assigns a thread to each request, which is the same business logic (member method) that multiple threads execute concurrently with the request, and it is important to note that if there is a modification to that single column state in that processing logic (which is reflected as a member property of that column), You must consider the comparison of the synchronization mechanism of thread synchronization problem threadlocal and the thread synchronization mechanism what advantages? Both the threadlocal and thread synchronization mechanisms are designed to address the access violation of the same variable in multiple threads. in the synchronization mechanism, the lock mechanism of the object guarantees that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when to lock an object, when to release object locks and other complex problems, programming and writing is relatively difficult. threadlocal The concurrent access to multithreading from another angle. Threadlocal provides a separate copy of the variable for each thread, isolating the access violation of multiple threads to the data. Because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides thread-safe shared objects that can encapsulate unsafe variables into threadlocal when writing multithreaded code. because the threadlocal can hold any type of object, the Get () provided by the lower version of the JDK returns an object, which requires a type cast. But JDK 5.0 through generics very good solves this problem, to a certain extent simplifies the use of threadlocal summed up that for multi-threaded resource sharing problem, the synchronization mechanism adopted the "time-to-space" approach, and threadlocal adopted the "space for Time" way. The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other. Spring uses threadlocal to resolve thread safety issues we know that in general, only stateless beans can be shared in a multithreaded environment, in spring, Most beans can be declared as singleton scopes. is because spring is for some beans (such as Requestcontextholder, TransactionsynchronizationmanAger, Localecontextholder, etc.) the non-thread-safe state is handled by threadlocal, making them also a thread-safe state, because stateful beans can be shared across multiple threads. General Web applications are divided into the presentation layer, the service layer and the persistence layer three levels, the corresponding logic is written in different layers, and the lower layer is called by the interface to the upper layer open function. In general, all program calls from receiving requests to returning responses belong to one threadThreadlocal is a good idea to solve thread safety problems by providing a separate copy of the variable for each thread to solve the conflicting problem of variable concurrency access. In many cases, threadlocal is easier and more convenient than using the synchronized synchronization mechanism to solve thread safety problems, and results programs have higher concurrency. If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. Or, the interface provided by a class or program for a thread is an atomic operation or a switchover between multiple threads does not result in ambiguity in the execution of the interface, that is, we do not have to consider the problem of synchronization.
thread safety issues are caused by global variables and static variables. In general, this global variable is thread-safe if there are only read operations for global variables and static variables in each thread, and if multiple threads are concurrently performing write operations, it is generally necessary to consider thread synchronization, which may affect thread safety. 1) constants are always thread-safe because only read operations exist. 2) Creating a new instance before each call to the method is thread safe because the shared resource is not accessed. 3) Local variables are thread-safe. Because each execution of a method creates a local variable in a separate space, it is not a shared resource. Local variables include the parameter variables of the method and the in-method variables. A state is a data storage function. Stateful objects (Stateful beans), which are objects with instance variables, can hold data that is non-thread safe. No state is preserved between different method invocations. Stateless is a single operation and cannot hold data. Stateless objects (stateless beans) are objects that do not have an instance variable. Cannot save data, is immutable class, is thread safe. Stateful objects: Stateless beans are suitable for invariant patterns, and technology is a singleton mode, which allows you to share instances and improve performance. Stateful beans, which are unsafe in multithreaded environments, are suitable for use with the prototype prototype model. Prototype: A new bean instance is created each time a request is made to the bean. STRUTS2 The default implementation is prototype mode. That is, each request is reborn as an action instance, so there is no thread safety issue. It is important to note that if the life cycle of the action is managed by spring, scope is to be paired with the prototype scope.
Annotations:
Spring Bean life cycle
The scope of the 1.Bean can be set through the scope property of the bean tag, and the scope of the bean includes:
By default scope= "Singleton", then the Bean is a singleton, and anyone getting the bean instance is the same instance;
Scope= "Prototype", any instance is a new instance;
Scope= "Request", in a Web application, the scope of each instance is the request scope;
Scope= "Session", in a Web application, each instance is scoped to the session;
Note: By default, the bean instance is instantiated when it is initialized by the spring container, and the parameterless construction method is called by default. In other cases, the bean will be instantiated when the instance is fetched .
Two, thread safety case:
There is a Calendar object reference inside the SimpleDateFormat (SDF) class that is used to store date information related to this SDF, such as Sdf.parse (DATESTR), Sdf.format (date) And so on. Parameters passed in date-related strings, dates, and so on, are all dating calendar is used to store. This will cause a problem, if your SDF is static, then multiple thread will share this SDF, Also share this calendar reference, and, observing the Sdf.parse () method, you will find a call like the following: Date parse () { calendar.clear ();//Cleanup calendar & nbsp ...//Perform some operations, set calendar date for what calendar.gettime (); The time to get the calendar } The problem here is that if thread A calls Sdf.parse () and does not perform calendar.gettime () after Calendar.clear (), Thread B also calls Sdf.parse (), when thread B executes the Sdf.clear () method, which causes the calendar data for thread A to be emptied (in fact, a, B is emptied). Or when a executes a calendar.clear () and is suspended, this is when B starts calling Sdf.parse () and ends with a smooth I, so that the date stored in the calendar of A is It becomes the date of the calendar that was set by B. The problem behind the question is a more important question-stateless: one of the benefits of a stateless approach is that it can be safely invoked in a variety of environments. To measure whether a method is stateful, see if it changes something else, such as a global variable, such as an instance field. The Format method changes the Calendar field of the SimpleDateFormat during the run, so it is stateful. This also reminds us to take note of the three-point: 1 when developing and designing the system. When you write a common class, make a note of the consequences of the multi-threaded invocation in the comments 2. For thread environments, be aware of thread safety 3 for each variable that is shared. Our classes and methods should be designed to be as stateless as possible when designing three. SolveMethods 1. Create a new instance when needed: description: When you need to use the SimpleDateFormat place a new instance, whenever, the thread security problem of the object from the share to local private can avoid multithreading problems, But it also adds to the burden of creating objects. In general, this is actually less noticeable than the performance impact. 2. Using sync: Synchronizing SimpleDateFormat objects public class Datesyncutil { private static SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); public static String FormatDate (date date) throws parseexception{ synchronized (SDF) { R Eturn Sdf.format (date); } } public static D Ate Parse (String strdate) throws parseexception{ synchronized (SDF) { return Sdf.parse (strdate); } } } Description: When a thread calls the method, other calls to the The thread of this method will block, the multi-thread concurrency is large when the performance has a certain impact. 3. Using threadlocal: public class concurrentdateutil { Private statIC threadlocal<dateformat> ThreadLocal = new threadlocal<dateformat> () { @ override protected DateFormat initialvalue () { return New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); } }; public Stati C Date Parse (String datestr) throws ParseException { return Threadlocal.get (). Parse (DATESTR); nbsp } public static String format (date date) { return Threadlocal.get (). f Ormat (date); }} or public class Threadlocaldateutil { private static final String Date_format = "yy Yy-mm-dd HH:mm:ss "; private static threadlocal<dateformat> ThreadLocal = new threadlocal< Dateformat> (); public static DateFormat GetDateFormat () { & nbsp DateFormat df =Threadlocal.get (); if (df==null) { /df = new SimpleDateFormat ( Date_format); Threadlocal.set (DF); } return DF; } public static String formatdate (date date) throws ParseException { & nbsp return GetDateFormat (). Format (date); } public static date parse (String StrD ATE) throws ParseException { return GetDateFormat (). Parse (strdate); }   ;} Description: Using threadlocal, the shared variable is also changed to exclusive, the thread exclusive can be compared to the method exclusive in the concurrency environment can reduce the cost of many objects created. This approach is generally recommended if performance requirements are high. 4. Discard the JDK and use time in other class libraries to format the class: 1. Using Fastdateformat in Apache Commons, claiming to be fast and thread-safe SimpleDateFormat, Unfortunately, it can only format the date and cannot parse the date string. 2. Use the Joda-time class library to handle time-related issues do a simple stress test, one of the slowest methods, the fastest method, but the slowest method of performance is not bad, the general system method one and two methods can be met, so said inThis point can hardly be the bottleneck of your system. From a simple point of view, it is recommended to use method one or method two, if necessary, the pursuit of a bit of performance improvement, you can consider using method three, with threadlocal cache.
Understanding of simple interest patterns in spring