当前位置:网站首页>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
边栏推荐
- NOI OJ 1.3 05:计算分数的浮点数值 C语言
- 个人博客系统毕业设计开题报告
- 大作业合集
- Implementing Domain Driven Design - using ABP framework - General guidelines
- [software and system security] heap overflow
- Install the typescript environment and enable vscode to automatically monitor the compiled TS file as a JS file
- 2021-05-07构造器
- 一个优秀速开发框架是什么样的?
- What is JSX in the JS tutorial? Why do we need it?
- Copilot免费时代结束!正式版67元/月,学生党和热门开源项目维护者可白嫖
猜你喜欢
随机推荐
thymeleaf如何取url中请求参数值?
pycharm安装教程,超详细
How to solve the problem that easycvr does not display the interface when RTMP streaming is used?
JVM简单入门-01
regular expression
Simple understanding of quick sort
mysql innodb 的 redo log buffer 中未 commit 的事务持久化到 redo log 后,万一事务 rollback 了怎么办?redo log 怎么处理这个事务操作?
2021-04-12 the first implementation of linked list!!!
2021-05-12接口的定义与实现
2021-05-07构造器
几款实用软件分享
Install the typescript environment and enable vscode to automatically monitor the compiled TS file as a JS file
STM32F1与STM32CubeIDE编程实例-红外寻迹传感器驱动
Bugs encountered in Oracle
文件IO(1)
验证码redis实践总结
[day 23] given an array of length N, insert element x into the position specified by the array | array insertion operation 4
【第23天】给定一个长度为 n 的数组,将元素 X 插入数组指定的位置 | 数组插入操作4
实现领域驱动设计 - 使用ABP框架 - 通用准则
天龙八部TLBB系列 - 网单服务端各目录文件说明【超详细】









