tomcat线程池和普通的线程池设计上有所区别,下面主要来看看它是如何设计的
tomcat中线程池的创建
org.apache.tomcat.util.net.AbstractEndpoint#createExecutor
tomcat创建线程池 public void createExecutor() { internalExecutor = true; // 任务队列和普通的队列有所区别,后续分析 TaskQueue taskqueue = new TaskQueue(); // 线程工厂用于创建线程 本地项目name=http-nio-port-exec-序号 TaskThreadFactory tf = new TaskThreadFactory(getName() + "-exec-", daemon, getThreadPriority()); // 创建线程池,注意这个ThreadPoolExecutor和java.util.concurrent包下的ThreadPoolExecutor有所区别 executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), 60, TimeUnit.SECONDS,taskqueue, tf); // 给任务队列设置线程池,用于后续任务来了判断是创建线程执行还是将线程添加到任务队列 taskqueue.setParent( (ThreadPoolExecutor) executor); }
tomcat的ThreadPoolExecutor
tomcat的ThreadPoolExecutor实际上继承了java包的ThreadPoolExecutor再其上定制了一些功能
submittedCount:记录了线程池中正有多少线程在执行任务(还没执行完)
lastContextStoppedTime:记录上次上下文停止的时间
lastTimeThreadKilledItself:记录线程上一次为防止内存泄漏自我kill的时间
构造方法:调用了父类ThreadPoolExecutor,同时调用了prestartAllCoreThreads方法,再完成线程池的创建后预热核心线程,使得任务到来时能够直接执行任务,不用再花时间去创建线程,提高了效率。
execute方法:执行executor方法时首先将 submittedCount加1,再调用父类的executor方法执行任务。若抛出RejectedExecutionException异常则再回尝试将任务添加到任务队列汇中
afterExecute:重写父类方法,任务执行完成后调用afterExecute钩子方法将 submittedCount减1,再尝试停止线程
contextStopping:若容器上下文停止,则会记录lastContextStoppedTime为当前时间并中断正在运行的线程。调用currentThreadShouldBeStopped方法的时候会判断线程TaskThread创建的时间是否在 lastContextStoppedTime之前,表示当前线程是在上一个上下文运行期间创建,则会尝试kill线程
public class ThreadPoolExecutor extends java.util.concurrent.ThreadPoolExecutor { /** * The string manager for this package. */ protected static final StringManager sm = StringManager .getManager("org.apache.tomcat.util.threads.res"); /** * The number of tasks submitted but not yet finished. This includes tasks * in the queue and tasks that have been handed to a worker thread but the * latter did not start executing the task yet. * This number is always greater or equal to {@link #getActiveCount()}. */ private final AtomicInteger submittedCount = new AtomicInteger(0); private final AtomicLong lastContextStoppedTime = new AtomicLong(0L); /** * Most recent time in ms when a thread decided to kill itself to avoid * potential memory leaks. Useful to throttle the rate of renewals of * threads. */ private final AtomicLong lastTimeThreadKilledItself = new AtomicLong(0L); /** * Delay in ms between 2 threads being renewed. If negative, do not renew threads. */ private long threadRenewalDelay = Constants.DEFAULT_THREAD_RENEWAL_DELAY; public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); prestartAllCoreThreads(); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Ru