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;
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 static boolean isRunning(int c) { return c < SHUTDOWN; }
private static boolean runStateAtLeast(int c, int s) { return c >= s; }
private boolean compareAndIncrementWorkerCount(int expect){
return ctl.compareAndSet(expect, expect + 1);
}
private boolean compareAndDecrementWorkerCount(int expect){
return ctl.compareAndSet(expect, expect - 1);
}
private void decrementWorkerCount() {
do {} while (!compareAndDecrementWorkerCount(ctl.get()));
}
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 int completedTaskCount;
private volatile ThreadFactory threadFactory;
private volatile RejectedExecutionHandler handler;
private volatile long keepAliveTime;
private volatile int corePoolSize;
private volatile int maximumPoolSize;
private volatile boolean allowCoreThreadTimeOut;
private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();
状态转换图
构造函数
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.acc = System.getSecurityManager() == null?null:AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
静态内部类
private final class Worker extends AbstractQueuedSynchronizer implements Runnable{
final Thread thread;
Runnable firstTask;
volatile long completedTasks;
Worker(Runnable firstTask){
setState(-1);
this.firstTask = firstTask;
this.thread = getThreadFactory().newThread(this);
}
public void run(){
runWorker(this);
}
protected boolean isHeldExclusively(){
return getState() != 0;
}
protected boolean tryAcquire(int unused){
if(compareAndSetState(0, 1)){
setExclusiveOwerThread(Thread.currentThread());
return true;
}
return false;
}
protected boolean tryRelease(int unused){
setExclusiveOwerThread(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(); }
void interruptIfStarted(){
Thread t;
if(getState() >= 0 && (t = thread) != null && !t.isInterrupted()){
try{
t.interrupt();
}catch(SecurityException ignore){}
}
}
}
public static class AbortPolicy implements RejectedExecutionHandler {
public AbortPolicy() {}
public void rejectedExecution(Runnable r, ThreadPoolExecutor e){
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
public static class DiscardPolicy implements RejectedExecutionHandler {
public DiscardPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
public DiscardOldestPolicy() { }
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
public static class CallerRunsPolicy implements RejectedExecutionHandler {
public CallerRunsPolicy(){}
public void rejectedExecution(Runnable r, ThreadPoolExecutor e){
if(!e.isShutdown()){
r.run();
}
}
}
重要方法
public <T> Future<T> submit(Callable<T> task){
if(task == null) throw new NullPointerException();
RunnableFuture<T> ftask = newTaskFor(task);
execute(ftask);
return ftask;
}
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable){
return new FutureTask<T>(callable);
}
public void execute(Runnable command){
if(command == null)
throw new NullPointerException();
int c = ctl.get();
if(workerCountOf(c) < corePoolSize){
if(addWorker(command, true) < corePoolSize)
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);
}
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 = false;
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();
}
}
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 new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
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;
}
}
}
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);
}
}
final void tryTerminated() {
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();
}
}
} 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;
}
}
}
}
private static void remove(Runnable task){
boolean removed = workQueue.remove(task);
tryTerminate();
return removed;
}
final void reject(Runnable command) {
handler.rejectedExecution(command, this);
}