首先确定Java线程池回收临时线程的基本思想,当一个线程在指定时间内无法从阻塞队列获取任务时,判断当前线程数是否超过最大线程数,超过则回收该线程。
具体代码实现部分如下:
首先是runWroker()部分,worker是线程池中事实上的线程,runWorker()方法是worker工作的核心方法,该方法会循环尝试从阻塞队列获取任务并执行,getTask()方法尝试从阻塞队列中获取任务,当满足回收条件(超时 && 超过核心线程数),会退出循环,执行线程回收工作.
final void runWorker(ThreadPoolExecutor.Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask; // 获取worker中的任务
w.firstTask = null; // 将worker中的任务置为空
w.unlock(); // allow interrupts
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);
}
}
getTask()方法如下, 其循环从阻塞队列中获取任务, 如果成功获取就返回; 否则, poll()方法会在超过限定时间后返回null, 触发判断机制, 此时如果工作线程数大于核心线程数, 就会返回null, 在runWroker()方法中回收工作线程.
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?
// timed 包含超过核心线程数
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) : // 关键,poll()方法可以设置超时参数,超时会返回null
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}