目录
前言
jdk的原生线程池会尽量保证核心线程数的线程运行,但对于io密集型任务,应尽量使用更多的线程,tomcat对线程池进行了扩展,本文主要针对tomcat线程池源码中的重点内容进行分析。
一、ThreadPoolExecutor
在tomcat的ThreadPoolExecutor中,对execute方法进行了重写,在当前任务被线程池拒绝时,会再次尝试将任务加入到等待队列中,尽可能保证任务能够被执行。
public void execute(Runnable command, long timeout, TimeUnit unit) {
//提交的任务数加一
submittedCount.incrementAndGet();
try {
//调用juc线程池的execute
super.execute(command);
} catch (RejectedExecutionException rx) {
//如果当前任务被拒绝,再次尝试加入到等待队列中
if (super.getQueue() instanceof TaskQueue) {
final TaskQueue queue = (TaskQueue)super.getQueue();
try {
if (!queue.force(command, timeout, unit)) {
//如果还是无法加入到队列中,提交任务数减一,抛出拒绝异常
submittedCount.decrementAndGet();
throw new RejectedExecutionException(sm.getString("threadPoolExecutor.queueFull"));
}
} catch (InterruptedException x) {
submittedCount.decrementAndGet();
throw new RejectedExecutionException(x);
}
} else {
submittedCount.decrementAndGet();
throw rx;
}
}
}
二、TaskQueue
tomcat中的taskQueue继承了LinkedBlockingQueue,为了线程池而设计,修改了offer方法,并且记录了当前提交到线程池中的任务数,在任务加入到队列的时候进行判断。在当前线程数小于最大线程数的时候,不会加入到队列中,返回false,从而会新建线程执行,尽可能创建多的线程执行任务。
public boolean offer(Runnable o) {
//we can't do any checks
if (parent==null) return super.offer(o);
//we are maxed out on threads, simply queue the object
// 如果当前线程数等于最大线程数,加入队列中
if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o);
//we have idle threads, just add it to the queue
// 如果当前提交的任务小于当前线程数,说明有线程空闲,加入队列中。
if (parent.getSubmittedCount()<=(parent.getPoolSize())) return super.offer(o);
//if we have less threads than maximum force creation of a new thread
// 如果当前的线程数小于最大线程数,返回false,线程池会创建新线程处理
if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false;
//if we reached here, we need to add it to the queue
//当前线程数大于最大线程数。。。。。
return super.offer(o);
}
总结
本文主要对tomcat中线程池的扩展进行了分析,内容比较多,没有全部覆盖,欢迎一块交流。