public class ThreadPoolExecutor extends AbstractExecutorService {
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;
/**
* RUNNING 可接受新任务,可处理已经进入阻塞队列的任务
* SHUTDOWN 不接受新任务,可处理已经进入阻塞队列的任务
* STOP 不接受新任务,不处理已经进入阻塞队列的任务并且中断正在运行的任务
* TIDYING 所有的任务都已经终止,workerCount为0, 线程转化为TIDYING状态并且调用terminated钩子函数
* TERMINATED terminated钩子函数已经运行完成
*/
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;
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 final BlockingQueue<Runnable> workQueue;
private final ReentrantLock mainLock =
new ReentrantLock();
private final HashSet<Worker> workers =
new HashSet<Worker>();
private final Condition termination = mainLock.newCondition();
private int largestPoolSize;
private long completedTaskCount;
private volatile ThreadFactory threadFactory;
private volatile RejectedExecutionHandler handler;
private volatile long keepAliveTime;
private volatile boolean allowCoreThreadTimeOut;
private volatile int corePoolSize;
private volatile int maximumPoolSize;
private static final RejectedExecutionHandler defaultHandler =
new AbortPolicy();
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
private static final long serialVersionUID =
6138294804551838833L;
final Thread thread;
Runnable firstTask;
volatile long completedTasks;
Worker(Runnable firstTask) {
setState(-
1);
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(
this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(
this);
}
protected boolean isHeldExclusively() {
return getState() !=
0;
}
protected boolean tryAcquire(
int unused) {
if (compareAndSetState(
0,
1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(
int unused) {
setExclusiveOwnerThread(
null);
setState(
0);
return true;
}
public void lock() { acquire(
1); }
public boolean tryLock() {
return tryAcquire(
1); }
public void unlock() { release(
1); }
public boolean isLocked() {
return isHeldExclusively(); }
}
final void tryTerminate() {
for (;;) {
int c = ctl.get();
if (isRunning(c) ||
runStateAtLeast(c, TIDYING) ||
(runStateOf(c) == SHUTDOWN && ! workQueue.isEmpty()))
return;
if (workerCountOf(c) !=
0) {
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();
}
}
}
private void interruptIdleWorkers(
boolean onlyOne) {
final ReentrantLock mainLock =
this.mainLock;
mainLock.lock();
try {
for (Worker w : workers) {
Thread t = w.thread;
if (!t.isInterrupted() && w.tryLock()) {
try {
t.interrupt();
}
catch (SecurityException ignore) {
}
finally {
w.unlock();
}
}
if (onlyOne)
break;
}
}
finally {
mainLock.unlock();
}
}
private void interruptIdleWorkers() {
interruptIdleWorkers(
false);
}
private boolean addWorker(Runnable firstTask,
boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
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();
if (runStateOf(c) != rs)
continue retry;
}
}
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 {
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask ==
null)) {
if (t.isAlive())
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;
}
private void addWorkerFailed(Worker w) {
final ReentrantLock mainLock =
this.mainLock;
mainLock.lock();
try {
if (w !=
null)
workers.remove(w);
decrementWorkerCount();
tryTerminate();
}
finally {
mainLock.unlock();
}
}
private void processWorkerExit(Worker w,
boolean completedAbruptly) {
if (completedAbruptly)
decrementWorkerCount();
final ReentrantLock mainLock =
this.mainLock;
mainLock.lock();
try {
completedTaskCount += w.completedTasks;
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;
}
addWorker(
null,
false);
}
}
private Runnable
getTask() {
boolean timedOut =
false;
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
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;
}
}
}
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 ((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);
}
}
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;
}
/**
* 进行下面三步
*
* 1. 如果运行的线程小于corePoolSize,则尝试使用用户定义的Runnalbe对象创建一个新的线程
* 调用addWorker函数会原子性的检查runState和workCount,通过返回false来防止在不应
* 该添加线程时添加了线程.
* 2. 如果一个任务能够成功入队列,在添加一个线程时仍需要进行双重检查(因为在前一次检查后
* 该线程死亡了),或者当进入到此方法时,线程池已经shutdown了,所以需要再次检查状态,
* 若有必要,当停止时还需要回滚入队列操作,或者当线程池没有线程时需要创建一个新线程.
* 3. 如果无法入队列,那么需要增加一个新线程,如果此操作失败,那么就意味着线程池已经shutdown
* 或者已经饱和了,所以拒绝任务.
*/
public void execute(Runnable command) {
if (command ==
null)
throw new NullPointerException();
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);
}
public void shutdown() {
final ReentrantLock mainLock =
this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(SHUTDOWN);
interruptIdleWorkers();
onShutdown();
}
finally {
mainLock.unlock();
}
tryTerminate();
}
}