"Go" Spring bean Singleton and thread safe

Source: Internet
Author: User

  

One, spring single case 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 when multithreaded development.

The singleton pattern means that there is only one instance, for example, in a spring container where there is only one instance of a class, and the entire system provides this instance, which is called a singleton class.

When multiple users request a service at the same time, the container assigns a thread to each request, and when multiple threads concurrently execute the business logic (the member method) of the request, it is important to note that thread synchronization must be considered if there is a modification to the singleton state in the processing logic (which is reflected as the member property of the Singleton).

Comparison of synchronization mechanisms:

What are the advantages of threadlocal compared to the thread synchronization mechanism? They are all in order to solve the problem of access violation of the same variable in multi-threading.

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, however, solves multiple threads of concurrent access 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 is a good solution to this problem through generics, in a way that simplifies the use of threadlocal to sum up, for multi-threaded resource sharing problems, The synchronization mechanism uses the "time-to-space" approach, while Threadlocal uses the "space-for-time" approach。    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 solve thread-safety problems 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,   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. The general Web application divides into the presentation layer, the service layer and the persistence layer three levels, writes the corresponding logic in the different layers, the lower layer through the interface to the upper layer open function calls. In general, all program calls from receiving requests to returning responses belong to one thread
Threadlocal 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 should be paired with prototype Scope II, 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, It is also shared with this calendar reference, non-thread safe.


There is a more important problem behind this 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 note the next three points when developing and designing the system:
1. When you write a common class, make a clear explanation of the consequences of the multi-threaded call case in the comments
2. Be aware of thread safety for each shared mutable variable in a threaded environment
3. Our classes and methods are designed to be as stateless as possible.
Workaround:

1. Use the Synchronized keyword for data synchronization, or use threadlocal to ensure thread safety

2. Do not use the time format class that comes with the JDK, using the other class library's

      • Using Apache Commons Fastdateformat, Xuancheng is a fast thread safe simpledateformat, but he can only format the date, cannot parse the date string
      • Use the Joda-time class library to deal with time-related problems, this kind of time processing method is more perfect, recommended to use .

Original link: https://www.cnblogs.com/redcool/p/6398760.html

"Go" Spring bean Singleton and thread safe

Related Article

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.