学习Java的线程池后一直想弄懂corePoolSize
、maximumPoolSize
和workQueue.size()
三者之间的关系。
在线程池中上述三个参数:
corePoolSize
:核心线程数,一直存活,除非设置了allowCorePoolTimeout=true
,将会在一定的超时时间keepAliveTime后被系统回收;maximumPoolSize
:最大线程数,当活动线程数达到这个数值后,后续的新任务将会被阻塞;workQueue
:任务队列,通过线程池的execute方法提交的Runnable对象来存储在这个参数中。
1、corePoolSize、maximumPoolSize的关系
ThreadPoolExecutor
构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
// 如果最大线程数 小于 核心线程数,抛异常
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
结论:从ThreadPoolExecutor的构造方法可以看出,maximumPoolSize
不能小于corePoolSize
。
2、corePoolSize、maximumPoolSize及workQueue容量的关系
execute方法如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
// 1. 如果当前线程数 小于 corePoolSize,则尝试添加新线程
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
// 添加成功,不会往下走
return;
c = ctl.get();
}
// 2. 尝试向workQueue添加队列(offer方法在workQueue没有容量时,添加失败),
// 线程已经存在不会创建新的线程,如果不存在则创建新的线程。
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 3. 添加新线程,此处会比较maximumPoolSize,如果大于maximumPoolSize,
// 则会使用饱和策略
else if (!addWorker(command, false))
// 4.执行饱和策略
reject(command);
}
其中addWorker方法如下,省略添加逻辑:
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
// 如果当前线程数 >= 最大容量,则添加失败
if (wc >= CAPACITY ||
// 如果当前线程数大于等于核心线程或最大线程池数,则添加失败
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
// 略...
}
涉及到的方法:
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
// runState is stored in the high-order bits
private static final int RUNNING = -1 << COUNT_BITS;
private static final int SHUTDOWN = 0 << COUNT_BITS;
private static int runStateOf(int c) { return c & ~CAPACITY; }
private static int workerCountOf(int c) { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }
private static boolean isRunning(int c) {
return c < SHUTDOWN;
}
结论:
从execute方法和addWorker方法可以看出,当前线程数优先与corePoolSize比较,大于corePoolSize,则与workQueue容量比较;
如果当前线程数大于workQueue容量,则与maximumPoolSize比较;
如果当前线程数大于maximumPoolSize,则执行饱和策略;
最后,根据饱和策略做出相应的处理。
3、饱和策略如下:
Abort策略:默认策略,新任务提交时直接抛出未检查的异常RejectedExecutionException
,该异常可由调用者捕获。
CallerRuns策略:为调节机制,既不抛弃任务也不抛出异常,而是将某些任务回退到调用者。不会在线程池的线程中执行新的任务,而是在调用exector的线程中运行新的任务。
Discard策略:新提交的任务被抛弃。
上述内容来源于:
(1)ThreadPoolExecutor中corePoolSize、maximumPoolSize及workQueue容量的关系
(2)java线程池的核心线程数与最大的线程数的区别,饱和策略
(3)理解ThreadPoolExecutor源码(一)线程池的corePoolSize、maximumPoolSize和poolSize