线上服务中有个使用 Spring 的scheduling.quartz的定时任务,每天凌晨1点向表里面灌初始数据,一个线程一台服务器在跑,刚上线的时候4个小时跑完,后来随着用户的激增,要下下午6点才结束,后来同事做了多线程优化,效果不显著,耗时依旧严重,Zzzzzzz~~~~
于是clone 代码看了下,感觉ExecutorService的使用怪怪的:
// 10个线程,因为任务多,这里用LinkedBlockingQueue private static final LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(); private static final ExecutorService service = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, queue );
ExecutorService 的参数定义:
1.当线程池小于corePoolSize时,新提交任务将创建一个新线程执行任务,即使此时线程池中存在空闲线程。
2.当线程池达到corePoolSize时,新提交任务将被放入workQueue中,等待线程池中任务调度执行
3.当workQueue已满,且maximumPoolSize>corePoolSize时,新提交任务会创建新线程执行任务
4.当提交任务数超过maximumPoolSize时,新提交任务由RejectedExecutionHandler处理
5.当线程池中超过corePoolSize线程,空闲时间达到keepAliveTime时,关闭空闲线程
容易产生错误的理解:
代码中的corePoolSize=0,也就是核心线程数是1,如果任务数多于10个,那么会先创建maximumPoolSize个线程执行,其余的任务加入 queue 中等待执行。
再看下类ThreadPoolExecutor中的注释:
* When a new task is submitted in method {@link #execute}, and fewer * than corePoolSize threads are running, a new thread is created to * handle the request, even if other worker threads are idle. If * there are more than corePoolSize but less than maximumPoolSize * threads running, a new thread will be created only if the queue is * full.
注意红色部分,而我们代码中的 queue 是个类似无界的LinkedBlockingQueue(其实是有界的,SIZE:Integer.MAX_VALUE)
queue 是不会 full 的,那么永远不会有maximumPoolSize个线程被创建,也就是说我们的任务一直还是一个线程在跑.......
果然只是把这个数字corePoolSize改为了3,耗时瞬间下降到了6、7个小时。又加了一台机器,依照业务主键的 ID 分布式跑任务,初始数据耗时缩减至3个小时左右!