ThreadPoolExecutor
在tomcat-embed-core
的jar包中org.apache.tomcat.util.threads;
包下面有ThreadPoolExecutor
,该类是Tomcat使用的线程池类。
Tomcat启动
WebServerStartStopLifecycle
在系统执行的时候会执行start
方法。
public void start() {
this.webServer.start();
this.running = true;
this.applicationContext.publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext));
}
NioEndpoint#startInternal
,当获取线程池获取不到,进行创建。
public void startInternal() throws Exception {
if (!this.running) {
this.running = true;
this.paused = false;
if (this.socketProperties.getProcessorCache() != 0) {
this.processorCache = new SynchronizedStack(128, this.socketProperties.getProcessorCache());
}
if (this.socketProperties.getEventCache() != 0) {
this.eventCache = new SynchronizedStack(128, this.socketProperties.getEventCache());
}
if (this.socketProperties.getBufferPool() != 0) {
this.nioChannels = new SynchronizedStack(128, this.socketProperties.getBufferPool());
}
if (this.getExecutor() == null) {
this.createExecutor();
}
this.initializeConnectionLatch();
this.poller = new NioEndpoint.Poller();
Thread pollerThread = new Thread(this.poller, this.getName() + "-Poller");
pollerThread.setPriority(this.threadPriority);
pollerThread.setDaemon(true);
pollerThread.start();
this.startAcceptorThread();
}
}
AbstractEndpoint#createExecutor
,创建线程池。核心线程池数为10,最大线程池数为200,活跃时间为60s,使用的队列是TaskQueue
。TaskQueue
是无界的阻塞队列。
public AbstractEndpoint() {
this.bindState = AbstractEndpoint.BindState.UNBOUND;
this.keepAliveTimeout = null;
this.SSLEnabled = false;
this.minSpareThreads = 10;
this.maxThreads = 200;
this.threadPriority = 5;
this.maxKeepAliveRequests = 100;
this.name = "TP";
this.daemon = true;
this.useAsyncIO = true;
this.negotiableProtocols = new ArrayList();
this.handler = null;
this.attributes = new HashMap();
}
public void createExecutor() {
this.internalExecutor = true;
TaskQueue taskqueue = new TaskQueue();
TaskThreadFactory tf = new TaskThreadFactory(this.getName() + "-exec-", this.daemon, this.getThreadPriority());
this.executor = new ThreadPoolExecutor(this.getMinSpareThreads(), this.getMaxThreads(), 60L, TimeUnit.SECONDS, taskqueue, tf);
taskqueue.setParent((ThreadPoolExecutor)this.executor);
}
Tomcat执行任务
ThreadPoolExecutor#execute()
- 当前运行的线程池小于核心线程数,
this.addWorker(command, true)
; - 大于核心线程池数,判断是否可以加入队列,调用的
TaskQueue
的offer方法; TaskQueue
的offer方法返回false,this.addWorker(command, false)
@Deprecated
public void execute(Runnable command, long timeout, TimeUnit unit) {
this.submittedCount.incrementAndGet();
try {
this.executeInternal(command);
} catch (RejectedExecutionException var9) {
if (!(this.getQueue() instanceof TaskQueue)) {
this.submittedCount.decrementAndGet();
throw var9;
}
TaskQueue queue = (TaskQueue)this.getQueue();
try {
if (!queue.force(command, timeout, unit)) {
this.submittedCount.decrementAndGet();
throw new RejectedExecutionException(sm.getString("threadPoolExecutor.queueFull"));
}
} catch (InterruptedException var8) {
this.submittedCount.decrementAndGet();
throw new RejectedExecutionException(var8);
}
}
}
private void executeInternal(Runnable command) {
if (command == null) {
throw new NullPointerException();
} else {
int c = this.ctl.get();
if (workerCountOf(c) < this.corePoolSize) {
if (this.addWorker(command, true)) {
return;
}
c = this.ctl.get();
}
if (isRunning(c) && this.workQueue.offer(command)) {
int recheck = this.ctl.get();
if (!isRunning(recheck) && this.remove(command)) {
this.reject(command);
} else if (workerCountOf(recheck) == 0) {
this.addWorker((Runnable)null, false);
}
} else if (!this.addWorker(command, false)) {
this.reject(command);
}
}
}
TaskQueue
TaskQueue#offer
,如果运行的线程数小于最大线程池数,返回false。
public boolean offer(Runnable o) {
if (this.parent == null) {
return super.offer(o);
} else if (this.parent.getPoolSize() == this.parent.getMaximumPoolSize()) {
return super.offer(o);
} else if (this.parent.getSubmittedCount() <= this.parent.getPoolSize()) {
return super.offer(o);
} else {
return this.parent.getPoolSize() < this.parent.getMaximumPoolSize() ? false : super.offer(o);
}
}
自定义线程配置
server.tomcat.threads.max=100
server.tomcat.threads.min-spare=30
TomcatServletWebServerFactory#customizeConnector
,创建WebServer
的时候,会对WebServer
定制化。
protected void customizeConnector(Connector connector) {
int port = Math.max(getPort(), 0);
connector.setPort(port);
if (StringUtils.hasText(getServerHeader())) {
connector.setProperty("server", getServerHeader());
}
if (connector.getProtocolHandler() instanceof AbstractProtocol) {
customizeProtocol((AbstractProtocol<?>) connector.getProtocolHandler());
}
invokeProtocolHandlerCustomizers(connector.getProtocolHandler());
if (getUriEncoding() != null) {
connector.setURIEncoding(getUriEncoding().name());
}
// Don't bind to the socket prematurely if ApplicationContext is slow to start
connector.setProperty("bindOnInit", "false");
if (getHttp2() != null && getHttp2().isEnabled()) {
connector.addUpgradeProtocol(new Http2Protocol());
}
if (getSsl() != null && getSsl().isEnabled()) {
customizeSsl(connector);
}
TomcatConnectorCustomizer compression = new CompressionConnectorCustomizer(getCompression());
compression.customize(connector);
for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) {
customizer.customize(connector);
}
}
TomcatWebServerFactoryCustomizer#customizeMaxThreads
,会自定义最大线程数数。
private void customizeMaxThreads(ConfigurableTomcatWebServerFactory factory, int maxThreads) {
factory.addConnectorCustomizers((connector) -> {
ProtocolHandler handler = connector.getProtocolHandler();
if (handler instanceof AbstractProtocol) {
AbstractProtocol protocol = (AbstractProtocol) handler;
protocol.setMaxThreads(maxThreads);
}
});
}