ThreadPoolExecutor
首先来看看线程池的主要工作流程图
接下来看看源码实现:
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;
// Packing and unpacking ctl
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; }
AtomicInteger的ctl变量,用低29位表示线程个数,高3位表示线程池状态;
- RUNNING :高三位:111,此时的线程池会接收任务,并处理阻塞队列中的任务;这里注意它其实是最小的
- SHUTDOWN:高三位:000,此时的线程池不会接收新的任务,但会处理阻塞队列中的任务。
- STOP:高三位:001,不接受新的任务,也不处理阻塞队列中的任务,而且中断正在执行的任务。
- TIDYING:010
- TERMINATED:011
我们使用Executor的execute(Runnable task)提交任务,但是它没有返回值,无法判断任务执行情况;而ExecutorService的submit(Callable task),返回Future,我们通过它来判断任务是否执行成功;
execute
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();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
- workerCountOf(c)获取低29位,也就是线程数,如果小于核心线程数,则调用addWork方法创建线程执行任务;否则执行步骤2
- 若当前线程池状态是RUNNING,则将任务添加到阻塞队列workQueue.offer(command)非阻塞,执行步骤3,否则执行步骤4;
- 由于加入队列操作的耗时,所以加进队列后会对当前线程池状态再次进行判断,若不在是RUNNING,则从队列中删除任务,再调用handler处理任务;
- addWorker(command, false)创建线程执行任务,执行失败则调用handler处理任务;
addWork
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
}
}
addWork就是创建线程执行任务的;我们前面说过,线程池有诸多状态,这些状态对应着线程池的行为;
代码逻辑:
- 如果状态大于等于SHUTDOWN,则不处理提交的任务直接返回
- 当前线程数要小于核心线程数或最大线程数,取决于你要创建什么线程,参数core为true则代表创建的是核心线程,使用循环CAS来确保线程个数增加操作的原子性;
接下来看看addWork源码的下半部分:
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) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}
上面的主要逻辑是,创建执行任务的Worker类,利用ReentrantLock 锁保证插入操作的原子性,指的是将Work插入到HashSet
Worker
/**
* Class Worker mainly maintains interrupt control state for
* threads running tasks, along with other minor bookkeeping.
* This class opportunistically extends AbstractQueuedSynchronizer
* to simplify acquiring and releasing a lock surrounding each
* task execution. This protects against interrupts that are
* intended to wake up a worker thread waiting for a task from
* instead interrupting a task being run. We implement a simple
* non-reentrant mutual exclusion lock rather than use
* ReentrantLock because we do not want worker tasks to be able to
* reacquire the lock when they invoke pool control methods like
* setCorePoolSize. Additionally, to suppress interrupts until
* the thread actually starts running tasks, we initialize lock
* state to a negative value, and clear it upon start (in
* runWorker).
*/
看注释,该类主要是控制在线程执行任务时的interrupt操作的。它继承了AbstractQueuedSynchronizer类,实现了一个非重入的锁。
为什么不用ReentrantLock,要用非重入的锁?因为不想让Worker里的任务在调用像setCorePoolSize这类线程池控制方法时能够再重新获取到锁;
Worker类:
1、继承了AQS类,可以方便的实现工作线程的中止操作;AQS维护了一个状态变量,这里Worker利用该变量,初始时设置为-1 ,w.unlock()改为0, w.lock()改为1;这些状态的改变跟ThreadPoolExecutor的shutdownNow有关,shutdownNow会调用interruptWorkers
private void interruptWorkers() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
for (Worker w : workers)
w.interruptIfStarted();
} finally {
mainLock.unlock();
}
}
里面会调用Worker的interruptIfStarted,worker将自己作为任务,线程start会调用runWork方法,该方法将状态变量由-1,变为0;此时线程拥有可被终止的资格,也就是只有运行的线程甭管它是否acquire成功,都可以中止。
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
从上面的逻辑可以看出,shutdownNow无论线程是在运行或是acquire失败被阻塞都可以中断。ThreadPoolExecutor里还有shutdown方法,无法中断正在运行的线程,也就是acquire成功的。
2、实现了Runnable接口,可以将自身作为一个任务在工作线程中执行;
3、当前提交的任务firstTask作为参数传入Worker的构造方法
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() {
runWorker(this);
}
runWorker
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // 允许中断
boolean completedAbruptly = true;
try {
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 {
processWorkerExit(w, completedAbruptly);
}
}
- 先通过w.unlock()将同步状态设为0,表示当前线程已经start,可以被中断了。
- 当前任务执行完就从阻塞队列中获取任务执行,任务执行用锁保护
- 在执行任务的前后,可以根据业务场景自定义beforeExecute和afterExecute方法;
- while循环一直获取任务,可以看出线程池会一直通过getTask提供任务让线程执行,getTask返回null,则表示该线程会被释放,如newCachedThreadPool所采取的策略。
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;
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;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
allowCoreThreadTimeOut :默认为false,表示允许核心线程空闲
举例子来说说不同策略是怎么利用getTask的:
newFixedThreadPool策略,核心线程数等于最大线程数,keepAliveTime = 0,它的timed一定为false,调用workQueue.take(),一直阻塞直到有新任务加到队列
newCachedThreadPool策略:没有核心线程数,时间为60秒,它的timed一定为true,调用workQueue.poll(keepAliveTime,TimeUnit.NANOSECONDS) ,等待60秒,时间一过返回null,timedOut = true, 由于getTask自旋,下次循环利用CAS将线程数减1,再返回null,runWorker退出循环,线程会被释放 ;
线程池监控
taskCount:线程池需要执行的任务数量。
completedTaskCount:线程池在运行过程中已完成的任务数量。小于或等于taskCount。
largestPoolSize:线程池曾经创建过的最大线程数量。通过这个数据可以知道线程池是否满过。如等于线程池的最大大小,则表示线程池曾经满了。
getPoolSize:线程池的线程数量。
getActiveCount:获取活动的线程数。
通过扩展线程池进行监控。通过继承线程池并重写线程池的beforeExecute,afterExecute和terminated方法,我们可以在任务执行前,执行后和线程池关闭前干一些事情。如监控任务的平均执行时间,最大执行时间和最小执行时间等。
参考文章
深入分析java线程池的实现原理
聊聊并发(三)Java线程池的分析和使用