/**
* Timeout in nanoseconds for idle threads waiting for work.
* Threads use this timeout when there are more than corePoolSize
* present or if allowCoreThreadTimeOut. Otherwise they wait
* forever for new work.
*/
private volatile long keepAliveTime;
/**
* Core pool size is the minimum number of workers to keep alive
* (and not allow to time out etc) unless allowCoreThreadTimeOut
* is set, in which case the minimum is zero.
*/
private volatile int corePoolSize;
如上,这两个参数分别是用来指定核心线程的个数,以及超过核心线程数之后,线程等待任务超时时间(超时没有领到任务,则会被回收)。
所以这个里面隐含了两个概念-- task(任务) 和 worker(做任务的工人,也就是上文提到的“线程”)。task其实就是提交上来的Runnable实现对象,如下:
/**
* Executes the given task sometime in the future. The task
* may execute in a new thread or in an existing pooled thread.
*
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
* {@code RejectedExecutionHandler}, if the task
* cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
*/
public void execute(Runnable command)
……
再来看下worker的源码,对核心线程的管理都包含在之内。
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
/**
* This class will never be serialized, but we provide a
* serialVersionUID to suppress a javac warning.
*/
private static final long serialVersionUID = 6138294804551838833L;
// 每一个task(Runnable)都需要一个Thread来start
/** Thread this worker is running in. Null if factory fails. */
final Thread thread;
/** Initial task to run. Possibly null. */
Runnable firstTask;
/** Per-thread task counter */
volatile long completedTasks;
……
那接下来看看核心线程数(核心worker数)是如何来保障的。
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
// 1.1 如果当前线程数小于核心线程数,则直接尝试创建核心worker,并把当前提交任务给它来启动
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
// 1.2 如果创建新worker失败,则首先尝试放入队列排队
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
// 1.2.1 如果线程池非运行状态,则尝试移除task,并调用拒绝策略回应请求
if (! isRunning(recheck) && remove(command))
reject(command);
// 1.2.2 如果运行中的线程数为0,则尝试添加非核心worker处理task
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 1.3 以上1.1、1.2都不凑效,则尝试添加非核心worker处理task;否则调用拒绝策略回应请求
else if (!addWorker(command, false))
reject(command);
}
如上,接到任务之后,线程池的策略无外乎这三种情况。所以保障核心线程的逻辑在addWorker里面,上代码。
private boolean addWorker(Runnable firstTask, boolean core) {
……
// 各种判断,CAS增加线程计数
……
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
// 此处是关键,对应Worker类的run方法
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
如上分析,看Worker类的run方法做了什么。
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 取自己创建时同时赋值的头部任务,否则调用getTask()获取任务
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
// 置空任务,等待回收
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
// 处理任务结束后||未获取到有效任务,worker的回收或保持工作
processWorkerExit(w, completedAbruptly);
}
}
如下getTask源码
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
// 2.2 超最大线程数||核心线程获取任务超时,且无排队任务待处理
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
// 2.1 从队列中未获取任务超时
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
如下processWorkerExit源码
// 此处是保持核心线程数关键所在
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
completedTaskCount += w.completedTasks;
// 每次用完都释放worker
workers.remove(w);
} finally {
mainLock.unlock();
}
tryTerminate();
int c = ctl.get();
if (runStateLessThan(c, STOP)) {
if (!completedAbruptly) {
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
if (min == 0 && ! workQueue.isEmpty())
min = 1;
if (workerCountOf(c) >= min)
return; // replacement not needed
}
// worker非正常结束,或者核心线程数未满足,则继续添加worker,等待从排队任务中获取任务
addWorker(null, false);
}
}
总结,运作的原理就是,每次处理完任务后(无论是超时没获取到任务或者成功启动了一个任务),
1)worker都会被从workers set中移除;
2)会根据当前工作的线程数目,判断要不要新建worker补充到set中等待获取任务。
所以,worker被创建要不然等待超时被回收,要不然执行完启动任务被回收。但是只要核心线程小于阈值,就会源源不断的有新worker加入到等待获取任务的set中。