【线程池】Tomcat线程池

版本:tomcat-embed-core-10.1.8.jar

前言

最近面试被问到 Tomcat 线程池,因为之前只看过 JDK 线程池,没啥头绪。在微服务横行的今天,确实还是有必要研究研究 Tomcat 的线程池

Tomcat 线程池和 JDK 线程池最大的不同就是它先把最大线程数用完,然后再提交任务到队列里面。强烈建议先弄懂 JDK 线程池原理再看本文,推荐阅读:深入理解线程池(ThreadPoolExecutor)——细致入微的讲源码。_if (workeradded) { t.start(); workerstarted = true-CSDN博客

Tomcat 线程池

先打开 tomcat 的 server.xml 看一下,发现 tomcat 支持配置最大和最小线程数:

    <!--The connectors can use a shared executor, you can define one or more named thread pools--><!--<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"maxThreads="150" minSpareThreads="4"/>-->

可配置的参数的中文说明如下:

图片

这里主要关注线程池实现类,默认为 org.apache.catalina.core.StandardThreadExecutor

org.apache.catalina.core.StandardThreadExecutor#startInternal

/*** 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 {
​// 创建 Tomcat 自定义的任务队列taskqueue = new TaskQueue(maxQueueSize);// 创建线程工厂TaskThreadFactory tf = new TaskThreadFactory(namePrefix, daemon, getThreadPriority());// 创建线程池executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), maxIdleTime, TimeUnit.MILLISECONDS,taskqueue, tf);executor.setThreadRenewalDelay(threadRenewalDelay);// 最关键的地方,没有这行代码,Tomcat 的线程池则会表现的和 JDK 的线程池一样taskqueue.setParent(executor);
​setState(LifecycleState.STARTING);
}

这段方法就是构建线程池的地方,关键参数如下:

图片

org.apache.tomcat.util.threads.ThreadPoolExecutor

public class ThreadPoolExecutor extends AbstractExecutorService {public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler) {if (corePoolSize < 0 ||maximumPoolSize <= 0 ||maximumPoolSize < corePoolSize ||keepAliveTime < 0) {throw new IllegalArgumentException();}if (workQueue == null || threadFactory == null || handler == null) {throw new NullPointerException();}this.corePoolSize = corePoolSize;this.maximumPoolSize = maximumPoolSize;this.workQueue = workQueue;this.keepAliveTime = unit.toNanos(keepAliveTime);this.threadFactory = threadFactory;this.handler = handler;
​prestartAllCoreThreads();}
​/*** Starts all core threads, causing them to idly wait for work. This* overrides the default policy of starting core threads only when* new tasks are executed.** @return the number of threads started*/public int prestartAllCoreThreads() {int n = 0;while (addWorker(null, true)) {++n;}return n;}
}

tomcat 的线程池的名字和 jdk 线程池的名字一样,千万别搞混了。从构造函数可以看到,tomcat 线程池在创建完成后会调用 prestartAllCoreThreads 方法对所有核心线程做一次预热

线程池执行

private void executeInternal(Runnable command) {if (command == null) {throw new NullPointerException();}/** Proceed in 3 steps:** 1. If fewer than corePoolSize threads are running, try to* start a new thread with the given command as its first* task.  The call to addWorker atomically checks runState and* workerCount, and so prevents false alarms that would add* threads when it shouldn't, by returning false.** 2. If a task can be successfully queued, then we still need* to double-check whether we should have added a thread* (because existing ones died since last checking) or that* the pool shut down since entry into this method. So we* recheck state and if necessary roll back the enqueuing if* stopped, or start a new thread if there are none.** 3. If we cannot queue task, then we try to add a new* thread.  If it fails, we know we are shut down or saturated* and so reject the task.*/int c = ctl.get();if (workerCountOf(c) < corePoolSize) {if (addWorker(command, true)) {return;}c = ctl.get();}if (isRunning(c) && workQueue.offer(command)) {int recheck = ctl.get();if (! isRunning(recheck) && remove(command)) {reject(command);} else if (workerCountOf(recheck) == 0) {addWorker(null, false);}}else if (!addWorker(command, false)) {reject(command);}}

查看 tomcat 线程池的 execute 方法,感觉非常眼熟,这不就是 jdk 线程池的代码吗?其实这里是在 workQueue#offer 做了文章

org.apache.tomcat.util.threads.TaskQueue

public class TaskQueue extends LinkedBlockingQueue<Runnable> {
​@Overridepublic boolean offer(Runnable o) {//we can't do any checksif (parent==null) { // 如果parent为空,和JDK线程池没区别return super.offer(o);}//we are maxed out on threads, simply queue the objectif (parent.getPoolSizeNoLock() == parent.getMaximumPoolSize()) { // 运行中的线程数等于最大线程数,任务入队return super.offer(o);}//we have idle threads, just add it to the queueif (parent.getSubmittedCount() <= parent.getPoolSizeNoLock()) { // 未完成线程数 <= 运行中的线程数,任务入队return super.offer(o);}//if we have less threads than maximum force creation of a new threadif (parent.getPoolSizeNoLock() < parent.getMaximumPoolSize()) { // 运行中的线程数量 < 最大线程数,返回失败,让它去创建线程return false;}//if we reached here, we need to add it to the queuereturn super.offer(o);}
}

总结

本文主要介绍了 Tomcat 线程池的运行流程,和 JDK 线程池的流程比起来,它确实不一样。

而 Tomcat 线程池为什么要这样做呢?其实就是因为 Tomcat 处理的多是 IO 密集型任务,用户在前面等着响应呢,结果你明明还能处理,却让用户的请求入队等待?这样不好。说到底,又回到了任务类型是 IO 密集型还是 CPU 密集型这个话题上来,比起去改 JDK 的线程池参数,Tomcat 线程池又给了我们一个新的思路

参考

每天都在用,但你知道 Tomcat 的线程池有多努力吗?

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1542598.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

二分+优先队列例题总结(icpc vp+牛客小白月赛)

题目 思路分析 要求输出最小的非负整数k&#xff0c;同时我们还要判断是否存在x让整个序列满足上述条件。 当k等于某个值时&#xff0c;我们可以得到x的一个取值区间&#xff0c;若所有元素得到的x的区间都有交集(重合)的话,那么说明存在x满足条件。因为b[i]的取值为1e9&…

Maven-一、分模块开发

Maven进阶 文章目录 Maven进阶前言创建新模块向新模块装入内容使用新模块把模块部署到本地仓库补充总结 前言 分模块开发可以把一个完整项目中的不同功能分为不同模块管理&#xff0c;然后模块间可以相互调用&#xff0c;该篇以一个SSM项目为目标展示如何使用maven分模块管理。…

没错,我给androidx修了一个bug!

不容易啊&#xff0c;必须先截图留恋&#x1f601; 这个bug是发生在xml中给AppcompatTextView设置textFontWeight&#xff0c;但是却无法生效。修复bug的代码也很简单&#xff0c;总共就几行代码&#xff0c;但是在找引起这个bug的原因和后面给androidx提pr却花了很久。 //App…

云手机的海外原生IP有什么用?

在全球数字化进程不断加快的背景下&#xff0c;企业对网络的依赖程度日益加深。云手机作为一项创新的工具&#xff0c;正逐步成为企业优化网络结构和全球业务拓展的必备。尤其是云手机所具备的海外原生IP功能&#xff0c;为企业进入国际市场提供了独特的竞争优势。 什么是海外原…

DNF Decouple and Feedback Network for Seeing in the Dark

DNF: Decouple and Feedback Network for Seeing in the Dark 在深度学习领域&#xff0c;尤其是在低光照图像增强的应用中&#xff0c;RAW数据的独特属性展现出了巨大的潜力。然而&#xff0c;现有架构在单阶段和多阶段方法中都存在性能瓶颈。单阶段方法由于域歧义&#xff0c…

如何使用 3 种简单的方法将手写内容转换为文本

手写比文本更具艺术性&#xff0c;这就是许多人追求手写字体的原因。有时&#xff0c;我们必须将手写内容转换为文本&#xff0c;以便于存储和阅读。本文将指导您如何轻松转换它。 此外&#xff0c;通常以扫描的手写内容编辑文本很困难&#xff0c;但使用奇客免费OCR&#xff…

视觉距离与轴距离的转换方法

1.找一个明显的参照物&#xff0c;用上方固定的相机拍一下。保存好图片 2.轴用定长距离如1mm移动一下。 3.再用上相机再取一张图。 4.最后用halcon 将两图叠加 显示 效果如下 从图上可以明显的看出有两个图&#xff0c;红色标识的地方。 这时可以用halcon的工具画一个长方形…

Cesium 绘制可编辑点

Cesium Point点 实现可编辑的pointEntity 实体 文章目录 Cesium Point点前言一、使用步骤二、使用方法二、具体实现1. 开始绘制2.绘制事件监听三、 完整代码前言 支持 鼠标按下 拖动修改点,释放修改完成。 一、使用步骤 1、点击 按钮 开始 绘制,单击地图 绘制完成 2、编辑…

误差评估,均方误差、均方根误差、标准差、方差

均方根误差 RMSE/RMS 定义 RMSE是观察值与真实值偏差的平方&#xff0c;对于一组观测值 y i y_i yi​ 和对应的真值 t i t_i ti​ R M S E 1 n ∑ i 1 n ( y i − t i ) &#xff0c;其中n是观测次数 RMSE\sqrt{\frac1n \sum_{i1}^n (y_i-t_i)} \text{&#xff0c;其中n是…

2.个人电脑部署MySQL,傻瓜式教程带你拥有个人金融数据库!

2.个人电脑部署MySQL&#xff0c;傻瓜式教程带你拥有个人金融数据库&#xff01; ‍ 前边我们提到&#xff0c;比较适合做量化投研的数据库是MySQL&#xff0c;开源免费。所以今天我就写一篇教程来教大家如何在自己的环境中部署MySQL。 在不同的设备或系统中安装MySQL的步骤…

局部凸空间及其在算子空间中的应用之四——归纳极限空间2

局部凸空间及其在算子空间中的应用之四——归纳极限空间2 前言一、归纳极限拓扑中极限的含义总结 数学的真理是绝对的&#xff0c;它超越了时间和空间。——约翰冯诺伊曼 前言 在上一篇文章中&#xff0c;我们讨论了归纳极限拓扑的概念和与连续线性算子有关的一个重要结论。认…

为什么编程很难?

之前有一个很紧急的项目&#xff0c;项目中有一个bug始终没有被解决&#xff0c;托了十几天之后&#xff0c;就让我过去协助解决这个bug。这个项目是使用C语言生成硬件code&#xff0c;是更底层的verilog&#xff0c;也叫做HLS开发。 项目中的这段代码并不复杂&#xff0c;代码…

postman控制变量和常用方法

1、添加环境&#xff1a; 2、环境添加变量&#xff1a; 3、配置不同的环境&#xff1a;local、dev、sit、uat、pro 4、 接口调用 5、清除cookie方法&#xff1a; 6、下载文件方法&#xff1a;

calibre-web报错:File type isn‘t allowed to be uploaded to this server

calibre-web报错&#xff1a;File type isnt allowed to be uploaded to this server 最新版的calibre-web在Upload时候会报错&#xff1a; File type isnt allowed to be uploaded to this server 解决方案&#xff1a; Admin - Basic Configuration - Security Settings 把…

2024PDF内容修改秘籍:工具推荐与技巧分享

现在我们使用PDF文档的频率越来越高了&#xff0c;很多时候收到的表格之类的资料也都是PDF格式的&#xff0c;如果进行转换之后编辑再转换为PDF格式还是有点麻烦的&#xff0c;那么pdf怎么编辑修改内容呢&#xff1f;这篇文章我将介绍几款可以直接编辑PDF文件的工具来提高我们的…

鸿蒙next 带你玩转鸿蒙拍照和相册获取图片

前言导读 各位网友和同学&#xff0c;相信大家在开发app的过程中都有遇到上传图片到服务器的需求&#xff0c;我们一般是有两种方式&#xff0c;拍照获取照片或者调用相册获取照片&#xff0c;今天我们就分享一个小案例讲一下这两种情况的实现。废话不多说我们正式开始 效果图…

安全带检测系统源码分享

安全带检测检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Visio…

Linux,uboot,kernel启动流程,S5PV210芯片的启动流程,DRAM控制器初始化流程

一、S5PV210芯片的DRAM控制器介绍、初始化DDR的流程分析 1、DRAM的地址空间 1)从地址映射图可以知道&#xff0c;S5PV210有两个DRAM端口。 DRAM0的内存地址范围&#xff1a;0x20000000&#xff5e;0x3FFFFFFF&#xff08;512MB&#xff09;&#xff1b;DRAM1:的内存地址范围…

HarmonyOS---权限和http/Axios网络请求

网络请求(http,axios) 目录 一、应用权限管理1.1权限的等级1.2授权方式1.3声明权限的配置1.4如何向用户进行申请 二、内置http请求使用三、Axios请求使用&#xff08;建议&#xff09;3.1 使用方式一3.2 使用方式二&#xff08;建议&#xff09; 一、应用权限管理 应用权限保护…

SpringCloud Alibaba之Seata处理分布式事务

&#xff08;学习笔记&#xff0c;必用必考&#xff09; 问题&#xff1a;Transactional 的9种失效场景&#xff1f; 1、介绍 1.1、简介 官网地址&#xff1a;Apache Seata 源码地址&#xff1a;Releases apache/incubator-seata GitHub Seata是一款开源的分布式事务解决…