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 troubleshoot thread safety We know that in general, only stateless beans can be shared in a multithreaded environment, and in spring, most beans can be declared as singleton scopes. is because spring is for some beans (such as Requestcontextholder, Transactionsynchronizationmanager, LocalecontextholderAnd so on) 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.
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 ...//Perform a Some operations, set the calendar date for what calendar.gettime (); Get calendar Time} The problem here is that if thread A calls Sdf.parse () and Calendar.clear () is not executed calendar.gettime (), 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 look at the next three points when developing and designing the system: 1. When you write a common class, make a clear description of the consequences of the multi-threaded invocation in the comments 2. For thread environments, be aware of the thread security of each shared mutable variable 3. Our classes and methods are designed, Try to design a stateless three. Workaround 1. Create a new instance when needed: Description: Simpledatef requiredOrmat where to create a new instance, you can avoid multithreading problems whenever you change the thread-safe object from shared to local private, 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 Simpledatef Ormat ("Yyyy-mm-dd HH:mm:ss"); public static String formatdate (date date) throws parseexception{ synchronized (SDF) { return Sdf.format ( Date); } } public static date parse (String strdate) throws parseexception{ synchronized (SDF) { RET Urn Sdf.parse (strdate); } } } Description: When a thread calls the method, the other thread that wants to call this method will block. Multi-threaded concurrency can have a certain impact on performance when it comes to large volumes. 3. Use Threadlocal:public class Concurrentdateutil { private static threadlocal<dateformat> threadLocal = new Threadlocal<dateformat> () {&NBsp @Override protected DateFormat initialvalue () { return new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); } }; &nbs P public static Date Parse (String datestr) throws ParseException { return Threadlocal.get (). Parse (DATESTR); } public static String format (date date) { return Threadlo Cal.get (). Format (date); }} or public class Threadlocaldateutil { private static final String Date_ Format = "Yyyy-mm-dd HH:mm:ss"; private static threadlocal<dateformat> ThreadLocal = new THREADLOCAL&L T;dateformat> (); public static DateFormat GetDateFormat () { DateFormat df = Threadlocal.get (); if (df==null) { &nbsP DF = new SimpleDateFormat (date_format); Threadlocal.set (DF); } return DF; } public static String formatdate (date date) throws ParseException { return GetDateFormat (). Format (date); } public static date parse (String strdate) th Rows parseexception { return GetDateFormat (). Parse (strdate); } } Description: Make With threadlocal, the shared variable is also changed to exclusive, and the thread-exclusive will definitely be able to save a lot of the overhead of creating objects in a concurrency environment compared to the method alone. This approach is generally recommended if performance requirements are high. 4. Discard the JDK and use time formatting classes from other class libraries: 1. Using Fastdateformat in Apache Commons, claiming to be a fast and thread-safe simpledateformat, unfortunately it can only format the date, The date string cannot be parsed. 2. Use the Joda-time class library to deal with time-related problems to do a simple stress test, one of the slowest method, the fastest method three, but the slowest method of a performance is not bad, the general system method one and two methods can be satisfied, so that in this point is difficult to become 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. Joda-time class Library is perfect for time processing, it is recommended.
Multithreaded Learning second bullet singleton mode and thread safety