private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
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 final int STOP = 1 << COUNT_BITS;
private static final int TIDYING = 2 << COUNT_BITS;
private static final int TERMINATED = 3 << COUNT_BITS;
运行状态 | 说明 |
---|---|
RUNNING | 能接受新任务提交,也能处理阻塞队列中的任务 |
SHUTDOWN | 关闭状态,无法接受新任务,但可以处理阻塞队列中的任务 |
STOP | 无法接受新任务且不会处理阻塞队列的任务,同时中断所有线程 |
TIDYING | 所有任务已取消,线程数量 (workerCount) = 0 |
TERMINATED | terminated() 执行完成后进入 TERMINATED 状态 |
1、当线程数小于核心线程数,创建新线程执行任务
2、当线程数大于等于核心线程数,尝试将任务放入阻塞队列
3、若放入阻塞队列失败
判断线程数是否小于最大线程数,若是,创建一个线程执行该任务,否则拒绝任务
4、若放入阻塞队列成功,结束
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();
// 当前线程小于核心线程 创建新核心线程执行该任务
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
// 线程数大于等于核心线程 尝试放入阻塞队列
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
// 双重校验 the pool shut down since entry into this method
if (! isRunning(recheck) && remove(command))
reject(command);
// 核心线程数为0 非核心线程刚好回收若不创建线程任务无法执行
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
// 线程数大于等于核心线程 放入队列失败 尝试创建非核心线程
else if (!addWorker(command, false))
reject(command);
}
/**
* A handler for tasks that cannot be executed by a {@link ThreadPoolExecutor}.
*
* @since 1.5
* @author Doug Lea
*/
public interface RejectedExecutionHandler {
/**
* Method that may be invoked by a {@link ThreadPoolExecutor} when
* {@link ThreadPoolExecutor#execute execute} cannot accept a
* task. This may occur when no more threads or queue slots are
* available because their bounds would be exceeded, or upon
* shutdown of the Executor.
*
* <p>In the absence of other alternatives, the method may throw
* an unchecked {@link RejectedExecutionException}, which will be
* propagated to the caller of {@code execute}.
*
* @param r the runnable task requested to be executed
* @param executor the executor attempting to execute this task
* @throws RejectedExecutionException if there is no remedy
*/
void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}
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;
/** 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;
/**
* Creates with given first task and thread from ThreadFactory.
* @param firstTask the first task (null if none)
*/
Worker(Runnable firstTask) {
setState(-1); // inhibit interrupts until runWorker
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
// Worker 执行逻辑:任务获取、执行
runWorker(this);
}
源码解析
// java.util.concurrent.ThreadPoolExecutor#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))
// WorkerCount CAS +1 成功 跳出循环进行 Worker 创建
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
// runState 发生变更 跳出循环重新判断状态进入
continue retry;
// else CAS failed due to workerCount change;
// 重新获取 workerCount 循环
retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
// 创建 Worker
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
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
// workerAdded success & start
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
// 线程池关闭 addWorkerFailed 处理逻辑
addWorkerFailed(w);
}
return workerStarted;
}
/**
* Rolls back the worker thread creation.
* - removes worker from workers, if present
* - decrements worker count
* - rechecks for termination, in case the existence of this
* worker was holding up termination
*/
private void addWorkerFailed(Worker w) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (w != null)
workers.remove(w);
decrementWorkerCount();
tryTerminate();
} finally {
mainLock.unlock();
}
}
源码分析
// java.util.concurrent.ThreadPoolExecutor#runWorker
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
// 是否存在 firstTask 需要执行
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
// worker died due to user exception
boolean completedAbruptly = true;
try {
// 存在 firstTask 或 从阻塞队列获取成功则继续执行
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);
}
}
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;
workers.remove(w);
} finally {
mainLock.unlock();
}
// tryTerminate 尝试调整线程池状态
tryTerminate();
int c = ctl.get();
// 如果线程池小于 STOP 状态
// 说明还可能继续执行任务
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
addWorker(null, false);
}
}
// 从阻塞队列获取任务
// getTask 一般会正常获取任务返回,当返回null会导致当前 Worker 销毁退出,有以下几种场景会返回null:
// 1、线程池处于STOP状态。这种情况下所有线程都应该被立即回收销毁;
// 2、线程池处于SHUTDOWN状态,且阻塞队列为空。不会有任务再提交到阻塞队列中。
// 3、当前线程数大于最大线程数(最大线程数调整)
// 4、线程空闲超时被回收:线程数大于核心线程数超时回收或核心线程允许超时回收
private Runnable getTask() {
// 标志 Worker 是否空闲过期 初始化为未过期
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.
// 如果线程池已经关闭 则直接返回 null
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
// 如果核心线程允许过期或大于核心线程数,则进行 Woker 过期处理
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
// wc > maximumPoolSize || (timed && timedOut) 返回 null
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 根据 timed 值判断是否一直阻塞等待任务还是keepAliveTime时间内阻塞
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
// Worker 空闲过期
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
源码分析
// java.util.concurrent.ThreadPoolExecutor#runWorker
try {
while (task != null || (task = getTask()) != null) {
// 执行任务
}
} finally {
// 获取不到任务时,主动回收自己
// 源码参考上文 Worker 执行
processWorkerExit(w, completedAbruptly);
}
// 关闭线程池 不再接受任务但会将已接收任务处理完
void shutdown();
// 关闭线程池 不再接受任务且不处理阻塞队列中的任务
// 返回阻塞队列中未处理的任务
List<Runnable> shutdownNow();
// 具体实现
// java.util.concurrent.ThreadPoolExecutor#shutdown
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// 权限检查
checkShutdownAccess();
// 将线程池状态置为 SHUTDOWN
advanceRunState(SHUTDOWN);
// Interrupts threads that might be waiting for tasks (as indicated by not being locked)
// 不中断正在执行任务的 Worker 继续执行完阻塞队列任务
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
// 尝试进入 TERMINATED 状态
tryTerminate();
}
// 和 shutdown() 方法逻辑基本一致
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 将线程池状态置为 STOP
advanceRunState(STOP);
// Interrupts all threads
// 中断所有 Worker
interruptWorkers();
tasks = drainQueue();
} finally {
mainLock.unlock();
}
tryTerminate();
return tasks;
}
/**
* Transitions to TERMINATED state if either (SHUTDOWN and pool
* and queue empty) or (STOP and pool empty). If otherwise
* eligible to terminate but workerCount is nonzero, interrupts an
* idle worker to ensure that shutdown signals propagate. This
* method must be called following any action that might make
* termination possible -- reducing worker count or removing tasks
* from the queue during shutdown. The method is non-private to
* allow access from ScheduledThreadPoolExecutor.
*/
final void tryTerminate() {
for (;;) {
int c = ctl.get();
// 1. 当前运行状态是 RUNNING 不设置TIDYING、TERMINATED
// 2. 或者 当前运行状态 处于 TIDYING 或者 TERMINATED, 那么也是暂时不设置TIDYING、TERMINATED
// 3. 或者 就是在 SHUTDOWN ,并且存在任务需要处理,那么也是暂时不设置TIDYING、TERMINATED
// 4. 否则 就是STOP,那么需要往下走
if (isRunning(c) ||
runStateAtLeast(c, TIDYING) ||
(runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
return;
// 执行到这里 说明处于 STOP 状态, 但是还存在工作线程没处理完,帮忙中断线程
// 如果线程数量不为0,则中断一个空闲的工作线程(把中断状态传播出去)
if (workerCountOf(c) != 0) { // Eligible to terminate
interruptIdleWorkers(ONLY_ONE);
return;
}
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (ctl.compareAndSet(c, ctlOf(TIDYING, 0))) {
try {
// 拓展点 由子类实现
terminated();
} finally {
ctl.set(ctlOf(TERMINATED, 0));
termination.signalAll();
}
return;
}
} finally {
mainLock.unlock();
}
// else retry on failed CAS
}
}
阅读量:2015
点赞量:0
收藏量:0