本篇主要从线程池的基本逻辑出发,然后深入研究了一些线程池的细节问题,弄清楚这些问题,才能更好的使用线程池。
第一:线程池基本逻辑
- 执行逻辑:使用线程池的伪代码如下。因为线程池最终是由线程来执行的,所以task还是需要实现runnable接口。
ThreadPool pool = new ThreadPool(100);
pool.execte(new Task());
class Task() implements Runnable{
public void run(){
...
}
}复制代码
- 管理方法:一个线程池是管理了很多个线程的一个对象, 所以不可避免的线程池还需要一系列的管理相关的方法,比如:线程池的线程怎么启动呢?线程池怎么关闭呢(需要等待正在执行的任务结束吗,如果任务长时间不结束怎么办)?我想获取线程池的状态怎么办(线程池现在跑的怎么样,有多少个线程在执行,执行了多少任务了,有多少任务在等待等等)?我想获取执行的结果怎么办 (上一篇介绍过的future机制)?线程池中的线程一直存活着吗还是需要keepalive timeout?所以不可避免的,我们需要加入如下管理方法
class ThreadPool{
public static int STATUS_INIT = 1;
public static int STATUS_RUN = 2;
public static int STATUS_CLOSING = 3;
public static int STATUS_CLOSED = 4;
public void init();//初始化 1
public void shutdown(); //关闭 2
public Status getStatus();//获取状态 3
public future execute();//执行 4
}复制代码
- 任务管理分配:我们想想怎么线程池使用的具体逻辑:首先使用者向线程池通过execute方法提交任务task,然后线程池执行,最后使用者通过future机制获取结果。有几个问题:分配任务给线程去执行的逻辑,线程池有100个线程,来了任务之后怎么分配,是轮询的进行分配,还是随机分配等等。线程池满了之后再来任务我们应该怎么办?用队列存放需要执行的任务还是直接拒绝?
- 实用feature:最后线程池需要有定时执行和周期执行的功能,以及批量执行等功能
上面这些都是线程池的一些必备的逻辑!很多文章都有提到,所以不深入进行分析。
第二:java线程池需要注意的细节
线程的提交阶段:
注意当线程数目大于corePoolSize之后,是将任务放入到队列之中,只有当队列存满了之后,如果此时线程数目小于maxPoolSize,才会新开线程进行执行! 这点需要注意,和我们直觉上有点差异!所以我们在使用的时候一定要根据负载来设定好队列的长度,否则maxPoolSize这个参数就失效了。具体代码如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {//1
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {//2
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))//3
reject(command);
}复制代码
如果线程数小于corePoolSize,那就新建一个线程来执行提交的任务,addWorker会原子的检查runState和 workerCount,防止创建出多的线程。当创建线程失败的时候返回false,比如两个创建的动作同时操作,但是只有一个能成功。
线程数大于corePoolSize,那么就放入workQueue中,然后recheck一下,如果发现线程池不在运行态了,就从队列中移除当前任务并且reject调用当前这个任务,目的就是防止任务不被执行,如果放进了队列并且再次检查线程池处于运行状态,那么就可以由线程池来确保该任务执行,提交者就不用担心了。如果线程池在运行态但是worker数目为0(具体场景可能是corePoolSize被设置成0的情况),那么就启动新线程来执行,这个recheck就是为了确定加入队列的任务确保能够执行。
如果将任务添加到队列失败,那么直接尝试添加worker来执行当前任务,如果添加失败说明线程池正在关闭中所以调用reject逻辑。这块可能要我写的话我就会将添加队列失败和线程池关闭两部分分别处理。
线程执行异常的处理
线程异常的处理可能很多人都没注意,如果我们在提交的runnable的run方法里面没有进行异常的处理怎么办?具体代码如下
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 (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();//1
} 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);
}
}复制代码
可以看到task.run方法实际上是被try catch住的,但是在被catch住之后又会被抛出来,所以如果我们在runnable的run方法里面没有处理异常的话实际上是会让worker跳出获取任务执行的循环,进而执行processWorkerExit方法的,如下
private void processWorkerExit(Worker w, boolean completedAbruptly) {
if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
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; // replacement not needed
}
addWorker(null, false);
}
}复制代码
核心逻辑就是做一些清理工作,把worker对象从worker集合中删除掉,worker对应的线程在出现异常后执行完上面的processWorkerExit方法之后就自动结束了,但是会执行thread对象里面uncaughtexceptionhandler。因为在jvm中如果一个线程的执行抛出了异常并且没有被捕获的话,那么该线程的执行会被终止,然后jvm会查看对应thread的uncaughtexceptionhandler来进行处理,所以可以通过set这个handler来进行个性化的异常定制,算是对异常的最后一道防线吧。所以如果出现了异常,线程池的线程就会死亡,然后下一次任务过来的时候就会重新建立线程!
worker实现了aqs,后面会分析aqs类(TODO),这是一大利器
private final class Worker extends AbstractQueuedSynchronizer implements Runnable复制代码
可以看到worker是aqs的子类,并且worker的初始的state设置成了-1, 这样在初始化的过程中就没有办法中断这个worker,直到runworker的时候将state设置成0之后才能进行中断worker。中断worker调用的是下面这个方法:必须要state>=0才能进行中断。这也比较好理解,一般中断线程就是想结束线程的执行,是想让线程从任务的获取-执行这一逻辑中进行中断,所以worker刚开始创建的时候就不允许中断,要不然创建就会失败。
void interruptIfStarted() {
Thread t;
if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
try {
t.interrupt();
} catch (SecurityException ignore) {
}
}
}复制代码
另外实现aqs的目的是在执行task的时候进行加锁,加锁的目的是为了防止task的执行时候修改了corepoolsize的数量或者调用别的某些方法导致需要中断worker的情况,代码如下:
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();
}
}复制代码
public void setCorePoolSize(int corePoolSize) {
if (corePoolSize < 0)
throw new IllegalArgumentException();
int delta = corePoolSize - this.corePoolSize;
this.corePoolSize = corePoolSize;
if (workerCountOf(ctl.get()) > corePoolSize)
interruptIdleWorkers();
else if (delta > 0) {
// We don't really know how many new threads are "needed".
// As a heuristic, prestart enough new workers (up to new
// core size) to handle the current number of tasks in
// queue, but stop if queue becomes empty while doing so.
int k = Math.min(delta, workQueue.size());
while (k-- > 0 && addWorker(null, true)) {
if (workQueue.isEmpty())
break;
}
}
}复制代码
如果corePoolSize数量变小了,那么就需要interrupt掉空闲的worker,interruptIdleWorkers方法如下:
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();
}
}复制代码
可以看到如果线程没有被中断,并且能够获取worker的lock,这个时候才去中断线程。如果worker在执行任务的过程中,那么worker是会持有aqs这个独占锁的,所以tryLock会返回失败,所以就不能中断正在执行task的任务。这也是符合逻辑的。也就是不能中断正在执行的worker。
线程池如何关闭
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}复制代码
这是文档给出的比较推荐的解决办法。但是一般需要自己根据业务逻辑来进行分析,找到合适的优雅的解决办法。
线程池任务队列
任务队列一般分为三种,一种是无界队列比如linkedblockingqueue,一种是有界队列比如arrayblockingqueue,一种是同步队列SynchronousQueue
同步队列会单独详解TODO