tomcat线程池与原生线程池的比较
jdk提供的线程池,当核心线程数已满,但是最大线程池数未满,来一个任务时,会先将任务加入阻塞队列。队列满之后才会创建线程来处理任务,这是比较适合cpu密集型任务的,但是像tomcat这种服务器程序就不太适合这种执行流程了。tomcat需要用户请求到达时马上就创建线程来处理,而不是加入阻塞队列。
先看看jdk原生线程池的执行流程。
1 public void execute(Runnable command) { 2 if (command == null) 3 throw new NullPointerException(); 4 /* 5 * Proceed in 3 steps: 6 * 7 * 1. If fewer than corePoolSize threads are running, try to 8 * start a new thread with the given command as its first 9 * task. The call to addWorker atomically checks runState and 10 * workerCount, and so prevents false alarms that would add 11 * threads when it shouldn't, by returning false. 12 * 13 * 2. If a task can be successfully queued, then we still need 14 * to double-check whether we should have added a thread 15 * (because existing ones died since last checking) or that 16 * the pool shut down since entry into this method. So we 17 * recheck state and if necessary roll back the enqueuing if 18 * stopped, or start a new thread if there are none. 19 * 20 * 3. If we cannot queue task, then we try to add a new 21 * thread. If it fails, we know we are shut down or saturated 22 * and so reject the task. 23 */ 24 int c = ctl.get(); 25 if (workerCountOf(c) < corePoolSize) { 26 if (addWorker(command, true)) 27 return; 28 c = ctl.get(); 29 } 30 if (isRunning(c) && workQueue.offer(command)) { 31 int recheck = ctl.get(); 32 if (! isRunning(recheck) && remove(command)) 33 reject(command); 34 else if (workerCountOf(recheck) == 0) 35 addWorker(null, false); 36 } 37 else if (!addWorker(command, false)) 38 reject(command); 39 }
第二步中workQueue.offer(command)这一步是核心,tomcat也是通过改造这一步来实现核心线程数满时来任务直接创建线程的方式的。
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); } }
参考:
原文链接:https://blog.csdn.net/weixin_41751625/article/details/116918956
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
2020-03-17 前端学习(53)~键盘事件
2020-03-17 前端学习(52)~事件委托
2020-03-17 前端学习(51)~事件的传播和事件冒泡
2020-03-17 前端学习(50)~事件的绑定和事件对象