推断 java 应用程序中线程增加的原因

Deduce why threads have increased in java application

上下文
我在服务器上有一个指标,它发布我在任何给定时间拥有的线程数量。在最近的部署中,我注意到线程数量平均增加了大约 30 个线程(最初停滞在 370 个左右,现在一直保持在 400 个线程)。

我做了什么
有许多 packages/possibilities 可能是这种增长的根本原因。这就是我研究分析线程的原因。我了解了如何获取和获取线程转储,但我看不到任何有用的信息,说明为什么使用这些线程 created/how。

我的服务没有受到负面影响 (latency/CPU/Memory),但我仍然想找出这个问题的根源,因为它可能是内存泄漏的原因。

我的问题
如果有一些资源能够获取创建线程的 class/package,那将非常有帮助(我在网上搜索了一段时间这样的资源)。

非常感谢任何针对根本原因的建议!

找到线程的来源

使用 Java Executors instead of dealing with Threads directly if you aren't already. If you are using Executors you can define names for the threads in your thread pool. These names are included in thread dumps of your java process. So if a thread has one of your custom defined names you will know which thread pool created it. It's common practice to maintain different thread pools for different types of tasks in your application and to give the threads in each pool different names. This way the you can determine how many threads each part of your application is creating when you take a thread dump. See this question 了解如何定义自定义线程名称。

如何限制线程

ThreadPoolExecutor允许您定义最大数量 池中的线程。因此,如果您知道您正在使用的所有池以及它们的最大大小是多少,您应该能够定义应用程序中可以 运行 的最大并发线程数。

您可能需要特别注意服务器、客户端和网络库,因为它们可能会创建自己的线程。库通常也会命名它们的线程,因此您可能 google 在线程转储中使用不熟悉的名称或堆栈跟踪来找出它的来源。