当前位置:网站首页>Experience of using thread pool in project
Experience of using thread pool in project
2022-06-23 10:25:00 【cfcoolya】
1 Summary of the application of thread pool in the project
1.1 background
In the work , Where thread pools are used is the ability to synchronize staff workload , This function is to select time synchronization personnel workload , The workload comes from the Zen system +Digiprocess System .
Normal is to initiate a workload request , Business logic processing , Response warehousing . There is a big disadvantage in this way, that is, one more request for data from other systems + Database operation , This in turn may result in slower response .
Use thread pool , Put the synchronization method in the queue , And then directly return the response , It will greatly improve the response speed of the interface .
1.2 Role of thread pool
Thread reuse
Thread Resource Management
Control the maximum concurrency of the operating system 、 To ensure the efficient and safe operation of the system
1.3 Thread pool core parameters
corePoolSize The number of threads in the core of the thread pool
maxmumPoolSize Thread pool the maximum number of thread pools
keepAliveTime When the thread exceeds corePoolSize, Extra free thread lifetime
unit KeepAliveTime The unit of
workQueue Task queue
threadFactory Thread factory
handler Refusal strategy , The queue is full , And the number of worker threads is greater than or equal to the maximum number of threads in the thread pool
1.4 working principle

1.5 Three important thread pools
newFixedThreadPool Fixed size thread pool , Perform long-term tasks
newSingleThreadExecutor The thread pool of a single thread
newCachedTreadPool Cacheable thread pool For short-term tasks
1.6 JDK Built in rejection strategy
AbortPolicy Direct selling rejectedExecutionException Exceptions prevent the system from functioning properly
CallerRunsPolicy Don't drop the mission , Call back some tasks to the caller
DiscarOldPolicy Discard the task waiting the longest in the queue , Then add the current task to the queue
DiscarPolicy Discard tasks directly
2 SpringBoot Creation of thread pool
2.1 Start class configuration
stay SpringBoot In the main program of @EnableAsync
2.2 To configure
@EnableAsync
@Configuration
public class TaskPoolConfig {
/**
* By default , After the thread pool is created , The number of threads in the thread pool is 0, When the mission comes , A thread is created to execute the task ,
* When the number of threads in the thread pool reaches corePoolSize after , The arriving task is placed in the cache queue ;
* When the line is full , Continue to create threads , When the number of threads is greater than or equal to maxPoolSize after , Start using the reject policy to reject
*/
@Value("${task.pool.corePoolSize}")
private Integer corePoolSize;// Set the number of core threads
@Value("${task.pool.maxPoolSize}")
private Integer maxPoolSize;// Set the maximum number of threads
@Value("${task.pool.keepAliveSeconds}")
private Integer keepAliveSeconds;// Set thread active time ( second )
@Value("${task.pool.queueCapacity}")
private Integer queueCapacity;// Set the queue capacity
@Bean("taskExecutor")
public Executor taskExecutor() {
// Create a thread pool
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// Number of core threads 10: The number of threads initialized when the thread pool is created
executor.setCorePoolSize(corePoolSize);
// Maximum number of threads 20: The maximum number of threads in the thread pool , Only after the buffer queue is full will it apply for more than the number of core threads
executor.setMaxPoolSize(maxPoolSize);
// Buffer queue 200: The queue used to buffer the execution of the task
executor.setQueueCapacity(queueCapacity);
// Allow free time for threads 60 second : When more than the core thread out of the thread in the idle time will be destroyed
executor.setKeepAliveSeconds(keepAliveSeconds);
// Prefix of thread pool name : After setting, it is convenient for us to locate the thread pool where the processing task is located
executor.setThreadNamePrefix("taskExecutor-");
// The processing strategy of the thread pool to reject the task :
// Here we use CallerRunsPolicy Strategy , When the thread pool has no processing power ,
// The strategy will be directly in execute Method to run a rejected task in the calling thread of the ;
// If the executing program is closed , The task will be discarded
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
@Async Will get threads from the thread pool by default , You can also explicitly specify @Async("asyncTaskExecutor")
2.3 properties To configure
### Thread pool
task.pool.corePoolSize=10
task.pool.maxPoolSize=20
task.pool.keepAliveSeconds=60
task.pool.queueCapacity=200
2.4 matters needing attention
The following way will make @Async invalid
The asynchronous method uses static modification
Asynchronous classes are not used @Component annotation ( Or other comments ) Lead to spring Cannot scan to asynchronous class
An asynchronous method cannot be in the same class as the called asynchronous method
Class @Autowired or @Resource Wait for the annotation to inject automatically , You can't do it by yourself new object
If you use SpringBoot The framework must add... To the startup class @EnableAsync annotation
边栏推荐
- Confessing with Snake games (with source code)
- 2021-05-07 package inheritance super this
- 同花顺推荐么?手机开户安全么?
- 2021-04-12 链表第一次实现!!!
- Musk's 18-year-old son petitioned to change his name to sever the father son relationship
- Install the typescript environment and enable vscode to automatically monitor the compiled TS file as a JS file
- RPC kernel details you must know (worth collecting)!!!
- IPv6 的速度比 IPv4 更快?
- NOI OJ 1.3 09:与圆相关的计算 C语言
- mysql innodb 的 redo log buffer 中未 commit 的事务持久化到 redo log 后,万一事务 rollback 了怎么办?redo log 怎么处理这个事务操作?
猜你喜欢

Set up a QQ robot for ordering songs, and watch beautiful women

Unity技术手册 - 生命周期内速度限制(Limit Velocity Over Lifetime)子模块和速度继承(Inherit Velocity)子模块

Lu Qi invests in quantum computing for the first time

搭建一个QQ机器人叫女友起床

卧槽,最惊艳的论文神器!

sql编写问题,求出当月和上月的环比值

汇编语言中断及外部设备操作篇--06

Solve the problem that Preview PDF cannot be downloaded

太无奈!微软停售 AI 情绪识别等技术,直言:“法律跟不上 AI 的发展”

Golang 快速上手 (1)
随机推荐
NOI OJ 1.4 04:奇偶ASCII值判断 C语言
漫画 | Code Review快把我逼疯了!
Shengshihaotong enables high-quality development with industrial Digitalization
马斯克 18 岁儿子请愿改名,欲断绝父子关系
Is there anyone who plans to open source an industrial "seckill" system architecture?
How does thymeleaf get the value of the request parameter in the URL?
Liujinhai, architect of zhongang Mining: lithium battery opens up a Xintiandi for fluorine chemical industry
2021-05-11抽象类
Different methods of PivotTable in SQL tutorial
JVM简单入门-01
Successful experience of postgraduate entrance examination in materials and Chemical Engineering (metal) of Beijing University of Aeronautics and Astronautics in 2023
搭建一个点歌QQ机器人,另外还能看美女
SQL create a new field based on the comparison date
Developer, you may have some misunderstandings about cloud computing
The second Tencent light · public welfare innovation challenge was launched, and the three competition topics focused on the social value of sustainable development
Unity技术手册 - 生命周期内速度限制(Limit Velocity Over Lifetime)子模块和速度继承(Inherit Velocity)子模块
2021-04-15
Golang 快速上手 (2)
AI芯片技术-2022年
What is JSX in the JS tutorial? Why do we need it?