如果任何请求在 tomcat 线程池中创建更多线程怎么办

What if any request create more thread in tomcat threadpool

假设 Tomcat 支持最多 5 个线程,并且 5 个线程正在进行中(假设这些请求会花费很多时间)。现在 1 个请求创建了 2 个线程来做某事,

  1. 所以这 2 个线程会得到 CPU 或者他们会等待?
  2. 如果他们等待,他们会在 OS 队列中等待吗? (接受连接队列)

这里是the documentation for maxThreads

The maximum number of connections that the server will accept and process at any given time. When this number has been reached, the server will accept, but not process, one further connection. This additional connection be blocked until the number of connections being processed falls below maxConnections at which point the server will start accepting and processing new connections again. Note that once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. The default value varies by connector type. For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO the default is 10000. For APR/native, the default is 8192.

线程限制是为 Tomcat 用于分配传入请求的内部池配置的最大数量。这不是 JVM 使用的线程数的硬性限制。

如果您的请求在其工作过程中创建更多线程(调用 new Thread()),这些线程不是来自池,而是来自 OS。

但最好的办法可能是使用单独的专用线程池。您始终可以配置自己的线程池,并让您的请求从该池中获取线程。这样你就不会 运行 系统线程不足(如果某些事情失控并且线程开始挂起,你可能会冒着创建新线程的风险)并且你不会减少 Tomcat处理请求的能力(如果您使用 Tomcat 的池,您会这样做)。