In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian for you to introduce in detail "against the use of Spring encapsulation of multithreaded class reasons", detailed content, clear steps, details handled properly, I hope that this "against the use of Spring encapsulation of multithreaded class reasons is what" article can help you solve doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.
Foreword:
It is inevitable that the work will be driven by failure, which actually turns on the violent use mode of the thread pool.
It is necessary for me to repeat it briefly. The main reason is that developers create a separate thread pool to handle with each method call. In this way, if the number of requests increases, the pressure on the entire operating system will be exhausted, and eventually all businesses will not be able to respond.
I have always thought that this is a very occasional low-level mistake, the frequency is very low. But as there are more and more such failures, xjjdog realizes that this is a common phenomenon.
For the purpose of asynchronous performance optimization, the result of the overall business unavailability is a very face-to-face optimization.
Asynchronous code for 1.Spring
As the leverage sub-framework of Java, Spring is deeply loved by developers because of its over-encapsulated API. According to the logic of semantic programming, as long as certain keywords are passable at the language level, we can add them. For example, the @ Async annotation.
I can never figure out what gives developers the courage to add this @ Async annotation, because such things that involve multithreading, even if they create their own threads, are in awe for fear of disturbing the peace of the operating system. Can a black box like @ Async really be used so smoothly?
We might as well debug the code and let the bullet fly for a while.
First, generate a small project, and then add the necessary comments to the main class. Well, don't forget this link, or the notes you add later will be of little use.
@ SpringBootApplication@EnableAsyncpublic class DemoApplication {
Create a method with @ Async annotations.
Componentpublic class AsyncService {@ Async public void async () {try {Thread.sleep (1000); System.out.println (Thread.currentThread ());} catch (Exception ex) {ex.printStackTrace ();}
Then, make a corresponding test interface, and the async method will be called when it is accessed.
@ ResponseBody@GetMapping ("test") public void test () {service.async ();}
When accessing, you can directly hit a breakpoint to get the thread pool that executes the asynchronous thread.
As you can see, the asynchronous task uses a thread pool, its corePoolSize=8, and the blocking queue uses an unbounded queue LinkedBlockingQueue. Once such a combination is adopted, the maximum number of threads will be null and void, because all tasks with more than eight threads will be placed in an unbounded queue. Make the following code become a decoration.
Throw new TaskRejectedException ("Executor [" + executor + "] did not accept task:" + task, var4)
If you have a very large number of visitors, these tasks will all pile up in LinkedBlockingQueue. If the situation is better, the execution of these tasks will become very late; if the situation is worse, too many tasks will directly cause memory overflow OOM!
You might say, I can specify another ThreadPoolExceute myself and declare it using the @ Async annotation. The students who say this must be more capable, or the code of Review is relatively less, and they have not been baptized by their teammates.
two。 It was SpringBoot who saved you.
SpringBoot is a good thing.
In TaskExecutionAutoConfiguration, the default Executor is provided by generating the Bean of the ThreadPoolTaskExecutor.
ConditionalOnMissingBean ({Executor.class}) public ThreadPoolTaskExecutor applicationTaskExecutor (TaskExecutorBuilder builder) {return builder.build ();}
That's what we're talking about above. Without the help of SpringBoot, Spring will use SimpleAsyncTaskExecutor by default.
See org.springframework.aop.interceptor.AsyncExecutionInterceptor.
@ Override@Nullableprotected Executor getDefaultExecutor (@ Nullable BeanFactory beanFactory) {Executor defaultExecutor = super.getDefaultExecutor (beanFactory); return (defaultExecutor! = null? DefaultExecutor: new SimpleAsyncTaskExecutor ();}
This is what Spring Tai Sin did.
The SimpleAsyncTaskExecutor class is poorly designed because each time it is executed, it creates a separate thread and there is no shared thread pool at all. For example, if your TPS is 1000 and you execute tasks asynchronously, you will generate 1000 threads per second!
This is obviously the rhythm of trying to kill the operating system.
Protected void doExecute (Runnable task) {Thread thread = (this.threadFactory! = null? This.threadFactory.newThread (task): createThread (task)); thread.start ();} 3.End
For discerning people, this way of using new threads will be very frightening. But in the case of Spring itself, there are many references to the class SimpleAsyncTaskExecutor, including the more popular AsyncRestTemplate.
This exposes a lot of risks, especially the fact that redis is seen in these lists. The design of this class makes the execution of tasks very uncontrollable.
Looking at this API, I feel that Spring has entered the magic state of design.
The hidden bug of this thing may be even deeper! For example, org.springframework.context.event.EventListener annotations are used to implement DDD's so-called event-driven pattern. There are many frameworks that directly set AsyncRestTemplate, so you're going to die.
Add SimpleAsyncTaskExecutor to your API blacklist or burial list!
Is it so difficult to create a thread? Need to use threads created by Spring? Sometimes I just can't figure out what the purpose of such an interface is.
Read here, this article "against the use of Spring encapsulation of multithreaded class reasons" article has been introduced, want to master the knowledge of this article still need to practice and use in order to understand, if you want to know more about the article, welcome to follow the industry information channel.
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.