线程池代码
@Configuration
public class ThreadPoolConfig
{
// 核心线程池大小
private int corePoolSize = 24;
// 最大可创建的线程数
private int maxPoolSize = 25;
// 队列最大长度
private int queueCapacity = 100;
// 线程池维护线程所允许的空闲时间
private int keepAliveSeconds = 300;
@Bean(name = "stockThreadPool")
public ThreadPoolTaskExecutor threadPoolTaskExecutor()
{
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setMaxPoolSize(maxPoolSize);
executor.setCorePoolSize(corePoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadGroupName("JM");
executor.setThreadNamePrefix("stock-thread-");
// 线程池对拒绝任务(无线程可用)的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
}
错误设置
压测:5000个文件同时处理,设置100个线程
压测结果:出现很多超时TIMED_WAITING
原因:如果线程数设置太多,会一直开辟新线程,如果GC自动回收来不及,会出现很超时线程,最后会引起OOM
正确设置
压测:5000个文件同时处理,设置10个线程
压测:5000个文件同时处理,设置10个线程
压测结果:线程都正常运行RUNNABLE
线程池设置多少合适