【源码解析】SpringWeb之Tomcat线程池源码剖析

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,使用的队列是TaskQueueTaskQueue是无界的阻塞队列。

    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);
			}
		});
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值