理解思路
我们开始在以下几个方面引入线程池。这里主要从上面的Service引入,保持上下文之间的联系,会很好的构建你的知识体系。 我们在上面了解到,Executor包含在Service中,Service中Executor的配置及相关代码如下:
server.service在xml中包含Executor的配置
executors在Service中的相关方法 /** * Adds a named executor to the service * @param ex Executor */ @Override public void addExecutor(Executor ex) { synchronized (executors) { if (!executors.contains(ex)) { executors.add(ex); if (getState().isAvailable()) { try { ex.start(); // 启动 } catch (LifecycleException x) { log.error(sm.getString("standardService.executor.start"), x); } } } } } /** * Retrieves all executors * @return Executor[] */ @Override public Executor[] findExecutors() { synchronized (executors) { Executor[] arr = new Executor[executors.size()]; executors.toArray(arr); return arr; } } /** * Retrieves executor by name, null if not found * @param executorName String * @return Executor */ @Override public Executor getExecutor(String executorName) { synchronized (executors) { for (Executor executor: executors) { if (executorName.equals(executor.getName())) return executor; } } return null; } /** * Removes an executor from the service * @param ex Executor */ @Override public void removeExecutor(Executor ex) { synchronized (executors) { if ( executors.remove(ex) && getState().isAvailable() ) { try { ex.stop(); // 停止 } catch (LifecycleException e) { log.error(sm.getString("standardService.executor.stop"), e); } } } } 和Server、Standardthreadexecutor也继承了Lifecyclembeanbase,Standardthreadexecutor;然后实现Executor接口。

Tomcat与Executor相关的配置文档
http://tomcat.apache.org/tomcat-9.0-doc/config/executor.html Executor接口设计
Executor的设计非常简单,理解时需要理解两点: Tomcat希望将Executor纳入Lifecycle生命周期管理,从而实现Lifecycle接口 引入超时机制,也就是说,当work 当queue满时,将等待指定的时间。如果超时,将抛出rejectedexecutionexception,因此这里将增加一个void execute(Runnable command, long timeout, TimeUnit unit)方法; 事实上,本质上,它在JUC中构建了ThreadPolexecutor,并通过它调用ThreadPolexecutorvoid execute(Runnable command, long timeout, TimeUnit unit)方法。 public interface Executor extends java.util.concurrent.Executor, Lifecycle { public String getName(); /** * Executes the given command at some time in the future. The command * may execute in a new thread, in a pooled thread, or in the calling * thread, at the discretion of the Executor implementation. * If no threads are available, it will be added to the work queue. * If the work queue is full, the system will wait for the specified * time until it throws a RejectedExecutionException * * @param command the runnable task * @param timeout the length of time to wait for the task to complete * @param unit the units in which timeout is expressed * * @throws java.util.concurrent.RejectedExecutionException if this task * cannot be accepted for execution - the queue is full * @throws NullPointerException if command or unit is null */ void execute(Runnable command, long timeout, TimeUnit unit); }
找到Executor的实现类

Standardthreadexecutor的实现
接下来我们来看看Standardthreadexecutor的具体实现。 了解相关配置参数
Executor官方配置说明文档 公共属性
Executor的所有实现 支持以下属性: 属性 描述 className 实现的类别。实现必须实现 org.apache.catalina.Executor接口。该接口确保引用对象并通过其name属性实现Lifecycle,以便使用容器启动和停止对象。clasname的默认值是org.apache.catalina.core.StandardThreadExecutor name 用于server.这个池的名字在xml的其他位置引用。这个名字是必要的,必须是唯一的。 Threadexecutor属性Standard
默认支持以下属性: 属性 描述 threadPriority (int)默认为执行程序中线程的线程优先级 5(Thread.NORM_PRIORITY常量值) daemon (boolean)默认情况下,线程是否应该是守护程序线程 true namePrefix (字符串)执行程序创建的每个线程的名称前缀。一个线程的线程名称将是namePrefix+threadNumber maxThreads (int)默认情况下,这个池中活动线程的最大数量是 200 minSpareThreads (int)默认情况下,最小线程数(空闲和活动)始终保持活动状态 25 maxIdleTime (int)空闲线程除非活动线程数小于或等于minsparethreads,否则关闭之前的毫秒数。默认值为60000(1分钟) maxQueueSize (int)最大数量的可操作任务可以在我们拒绝之前排队等待执行。默认值是Integer.MAX_VALUE prestartminSpareThreads (boolean)启动executor时是否应该启动minsparethreads?默认值为 false threadRenewalDelay (long)如果配置了ThreadlocalleakPreventionlistener,它将通知该执行程序已停止的上下文。上下文停止后,池中的线程将更新。为了避免所有线程同时更新,在任意两个线程续订之间设置延迟。以ms为单位,默认值为1000ms。如果值为负,则不会续订线程。 Lifecycle模板方法
先看核心变量: // 任务队列 private TaskQueue taskqueue = null; // ThreadPolexetor包装 protected ThreadPoolExecutor executor = null; Initinternal和destroyinternal默许父亲实现 @Override protected void initInternal() throws LifecycleException { super.initInternal(); } @Override protected void destroyInternal() throws LifecycleException { super.destroyInternal(); } startinternal方法
在这种方法中,不难看出,它是ThreadPolexecutor的初始化,同时构建ThreadPolexecutor的实例,后面TomcatStandThreadexecutor的实现本质上是通过ThreadPolexecutor实现的。 /** * Start the component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected void startInternal() throws LifecycleException { taskqueue = new TaskQueue(maxQueueSize); TaskThreadFactory tf = new TaskThreadFactory(namePrefix,daemon,getThreadPriority()); executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf); executor.setThreadRenewalDelay(threadRenewalDelay); if (prestartminSpareThreads) { executor.prestartAllCoreThreads(); } taskqueue.setParent(executor); setState(LifecycleState.STARTING); } stopinternal方法
代码非常简单,关闭线程池后的null, GC回收方便。 /** * Stop the component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that needs to be reported */ @Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); if (executor != null) { executor.shutdownNow(); } executor = null; taskqueue = null; } 核心executo方法
本质上是调用ThreadPolexecutor实例的相关方法。 @Override public void execute(Runnable command, long timeout, TimeUnit unit) { if (executor != null) { executor.execute(command,timeout,unit); } else { throw new IllegalStateException(sm.getString("standardThreadExecutor.notStarted")); } } @Override public void execute(Runnable command) { if (executor != null) { try { executor.execute(command); } catch (RejectedExecutionException rx) { //there could have been contention around the queue if (!((TaskQueue) executor.getQueue()).force(command)) { throw new RejectedExecutionException(sm.getString("standardThreadExecutor.queueFull")); } } } else { throw new IllegalStateException(sm.getString("standardThreadExecutor.notStarted")); } } 线程池的动态调整
我们还注意到,Standardthreadexecutor也实现了resizeablexecutor,从名称上我们可以知道它是想实现对线程池的动态调整,因此,它包装了resizeableexecutor接口,查看接口。 public interface ResizableExecutor extends Executor { /** * Returns the current number of threads in the pool. * * @return the number of threads */ public int getPoolSize(); public int getMaxThreads(); /** * Returns the approximate number of threads that are actively executing * tasks. * * @return the number of threads */ public int getActiveCount(); public boolean resizePool(int corePoolSize, int maximumPoolSize); public boolean resizeQueue(int capacity); }
前三种方法比较简单,我们来看看后两种方法是如何实现的, 其实也很简单。 @Override public boolean resizePool(int corePoolSize, int maximumPoolSize) { if (executor == null) return false; executor.setCorePoolSize(corePoolSize); executor.setMaximumPoolSize(maximumPoolSize); return true; } // 默认情况没有实现 @Override public boolean resizeQueue(int capacity) { return false; } 补充TaskQueuee
众所周知,工作队列是由TaskQueue保证的,它集成自LinkedBlockingQueue(一个阻塞链表队列),看下源代码。 /** * As task queue specifically designed to run with a thread pool executor. The * task queue is optimised to properly utilize threads within a thread pool * executor. If you use a normal queue, the executor will spawn threads when * there are idle threads and you wont be able to force items onto the queue * itself. */ public class TaskQueue extends LinkedBlockingQueue
TaskQueue这个任务队列是专门为线程池设计的。优化任务队列,适当利用线程池执行器中的线程。
如果使用普通队列,当有空闲线程executor时,会产生线程,不能强制将任务添加到队列中。 为什么不直接使用ThreadPolexecutor呢?
你有没有想过Tomcat为什么要自己构建一个StandardThreadExecutor,而不是直接使用ThreadPoolExecutor?
从上面的代码中,你会发现这里只使用executor,只使用execute的两种主要方法。它希望使调用层屏蔽threadPolexecutor的其他方法:
它所反映的原则:至少知识原则: 只和你的密友交谈。也就是说,客户对象需要交互的对象应该尽可能少
其设计模式:结构型 - 外观(Facade):外观模式(Facade pattern),它为访问子系统中的一组接口提供了一个统一的接口,使子系统更容易使用