该类是JDK中提供的线程池的实现,可以根据业务需求配置合适的参数,这样可以提高线程池的性能,该线程池的使用在前面的文章中已经讲解过了,本节主要分析其实现的机制是如何的。
如果让开发者自己设计线程池,肯定也会提出下面几个问题:
1、在初始化的时候,线程池的初始化大小。
2、当线程池中线程不够用了,线程池如何处理。
3、线程池中只有很少或者没有任务运行的时候,线程池中空闲的线程该如何处理。
接下来将围绕这三个问题分析ThreadPoolExecutor是如何实现的。
1、线程池初始化大小
在ThreadPoolExecutor提供了corePoolSize、maximumPoolSize等参数提供应用开发者配置线程的线程数量,并使用了HashSet<Worker>
来存放工作线程。Worker类是工作线程实现类,也是ThreadPoolExecutor中的内部类。
/**
* Set containing all worker threads in pool. Accessed only when
* holding mainLock.
*/
// 该集合主要存放了线程池的工作线程
private final HashSet<Worker> workers = new HashSet<Worker>();
woker类:
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. */
// 工作线程的Thread
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;
// 通过线程工程创建线程,并把自己传递到Thread中
this.thread = getThreadFactory().newThread(this);
}
/** Delegates main run loop to outer runWorker */
public void run() {
// runWorker是ThreadPoolExecutor的方法,该方法无限循环的从任务队列中获取任务并执行
runWorker(this);
}
// Lock methods
//
// The value 0 represents the unlocked state.
// The value 1 represents the locked state.
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(); }
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}
}
通过分析该Worker类可以发现,worker类中的run方法调用了ThreadPoolExecutor的runWorker方法,该方法会无限循环的从workQueue中获取任务执行
/**
* The queue used for holding tasks and handing off to worker
* threads. We do not require that workQueue.poll() returning
* null necessarily means that workQueue.isEmpty(), so rely
* solely on isEmpty to see if the queue is empty (which we must
* do for example when deciding whether to transition from
* SHUTDOWN to TIDYING). This accommodates special-purpose
* queues such as DelayQueues for which poll() is allowed to
* return null even if it may later return non-null when delays
* expire.
*/
// 主要存放了应用添加到线程池的任务
private final BlockingQueue<Runnable> workQueue;
2、线程池的线程创建、分配过程,以及线程不够用的时候如何处理
通过分析ThreadPoolExecutor的execute方法可以了解该过程是如何处理的:
/**
* 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) {
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.(如果无法将任务添加到任务队列,那么抛出rejectedExecution)
*/
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);
}
3、空闲线程如何处理
在上面提到工作线程调用ThreadPoolExecutor的runWorker方法获取任务执行,所以线程是否空闲也可以在该方法中进行(没有任务执行就代表空闲了,空闲的线程根据配置的参数进行释放)
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 当没有执行的时候跳出while循环(重点在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 {
// 然后执行线程退出操作
processWorkerExit(w, completedAbruptly);
}
}
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;
// 当前线程池的数量超过最大线程数量,或者是当前线程已经超时,那么返回空,runWorker会根据返回null,然后关闭当前线程
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 在线程上阻塞keepAliveTime(线程空闲最大时间)
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}