package com.cnabc.base.threadpool.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class ThreadPoolTaskExecutorConfig {
/**
* 参数初始化
*/
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
/**
* 核心线程数量大小
*/
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
@Value("${spring.application.name:cnabc}")
private String threadGroupName;
@Value("${thread.pool.namePrefix}")
private String threadNamePrefix;
/**
* 线程池最大容纳线程数
*/
@Value("${thread.pool.maxSize:0}")
private int maxSize;
/**
* 线程空闲后的存活时长
*/
@Value("${thread.pool.keepAliveTime:30}")
private int keepAliveTime;
@Bean
public ThreadPoolTaskExecutor initExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
taskExecutor.setMaxPoolSize(getMaximumPoolSize());
taskExecutor.setQueueCapacity(1000);
taskExecutor.setKeepAliveSeconds(keepAliveTime);
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.initialize();
taskExecutor.setThreadGroupName(threadGroupName);
taskExecutor.setThreadNamePrefix(threadNamePrefix);
return taskExecutor;
}
private int getMaximumPoolSize() {
return this.maxSize == 0 ? (CPU_COUNT * 2 + 1) : maxSize;
}
}