In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-05-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you springboot how to ensure multi-thread safety, I hope you will gain something after reading this article, let's discuss it together!
How to ensure multi-thread security? how does 1.springboot do under multi-thread concurrent access
Under Controller, we usually have @ AutoWired some Service, because these Service are all managed by spring, so they singleton, for calling their method in Controller, because the method belongs to stack operation in JVM, the stack is independent for each thread, so it is thread-safe.
Because Controller itself is singleton mode (non-thread safe), this means that every request comes over, the system will use the original instance to deal with, which leads to two results: one is that we do not have to create Controller every time, and the other is to reduce the time of object creation and garbage collection. Because there is only one instance of Controller, when multiple threads call it, the instance variable in it is not thread-safe, and the problem of data channeling occurs.
If we define a global instance, such as private Company company = new Company (), and use it in the @ RequestMapping method, there is a concurrency thread safety problem.
This company object is common to all request request.
Of course, we can also use this feature to make access counters by defining a private int cout = 0; cout++ after each request
Of course, I don't recommend it. Counters are best operated with redis.
To sum up the above problems, do not show instances of classes in Controller. Even if thread-safe operations are added, performance problems can occur. Of course, whether it's Controller or Service, if you must use the properties of the object, such as private Company company = new Company (); you can add a reference to ThreadLocal, such as private ThreadLocal tc = new ThreadLocal (); but initialize the object used in the method (that is, it's better to enter the JVM stack).
How to ensure thread safety and trade-off of 2.controller under multithreading as much as possible
When multiple requests make requests to controller, the singleton mode of its instance is not thread safe, so if we want to ensure complete thread safety, we need to create a new controller instance for each request, and use the @ RequestScope annotation in spring to define its scope as requst, that is, a request is an instance, so as to ensure thread safety at the controller level. But this has a big disadvantage, that is, when the concurrency is large, it is much slower to create a new instance of bean than to use the original controller instance.
Therefore, there is a compromise, that is, to set @ RequestScope to the scope of session level, so that every session, spring will create a controller instance instead of creating an instance for each request, which greatly improves the speed of access. Although this cannot guarantee absolute thread safety, it effectively prevents thread safety problems in most business logic.
In addition, the scope of spring is singleton (singleton, which is also the default scope level of spring, that is, always use the same instance), prototype (prototype), and globalSession (global).
3. Make a brief summary
Spring itself does not solve the problem of concurrent access. If the scope of bean is not thread-safe (for example, member variables or static variables above controller are thread-safe), but its method contains some critical code that you always want to run safely or uses static fields that need to be modified concurrently, use the synchronized keyword on this method. Or use some collections that provide thread safety for corresponding multithreading operations.
Singleton mode and thread safety problems
Recently, some customers reported that when using the company's products, there would be occasional crashes, and there was no problem with their own tests, and then they went to check the log, which was a null pointer. So look up, well, before the development of the use of member variables, I think this is the problem, because it is well known that springboot uses a singleton mode, so you must be careful when using member variables.
The last screenshot of this class below
As you may see, there is a @ Scope ("prototype") annotation on top of the class, which turns the class into a multi-instance schema. Reason because it has become more than one example, there should be no thread problems.
Let me first talk about a code environment on my side. The BaseController class you see above has an init method that executes before all the methods of the class inherit it.
The @ ModelAttribute annotation is used, which means that it is executed before all the methods of the controller, intended to initialize. I guess the previous colleague should be pulled out to be a parent class in order to get the same parameters. With the iteration, other colleagues use it for convenience, resulting in many controller inheriting this class.
@ Scope ("prototype") comment: imagine what happens if the parent class adds the @ Scope ("prototype") annotation, but the subclass controller does not? Does the note still make sense? For example, if I annotate a service with @ Scope ("prototype"), but the called controller does not add @ Scope ("prototype"), what will happen? You can test it, and the test method is also very simple, which is to print the address of this class in the corresponding parent class or service's no-parameter constructor.
Let's talk about my test results: first, @ Scope ("prototype") is annotated on the parent class, but not on the subclass. As a result, the same subclass inherits from the same parent class, and different subclasses inherit from different parent classes. Understand, very simple, because springboot is a singleton pattern, so the subclass is a singleton, then there is only one subclass, and the parent class must be the same. Therefore, different threads come to use the same variable, there will be a problem.
Similarly: mark @ Scope ("prototype") on the service, then the service is the same in the same controller, that is, it is a singleton, and it is different in different controller. The test method is the same as above.
Now talk about the solution.
1. Add @ Scope ("prototype") annotations to all subclasses that inherit the controller. The advantage of this is simplicity. The disadvantages are also obvious, because there are many cases, then it will produce a large number of entity classes and take up a lot of memory. If the recycling is not timely, there may be a memory overflow.
2, is to privatize variables, such as using thread variables, locking variables, etc., which will be technically complicated, and debugging is not easy to debug. Maybe there will be problems in those places, after all, it is the old code.
3. Convert this class into an interceptor, put the variable into request and take it out when you use it.
After reading this article, I believe you have a certain understanding of "how to ensure multi-thread safety in springboot". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.