java 线程转储中的高线程数

High thread count in java thread dump

我的 java Web 应用程序 运行 在 wildfly-9.0.1.Final 上有时会消耗非常高的内存和 CPU。 这次我得到了线程转储,发现超过 7K 个线程具有相同的线程,但堆栈跟踪如下。

pool-47940-thread-1 - priority:5 - threadId:0x000000029ad3f800 - nativeId:0xfad0 - state:WAITING
stackTrace:
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000007a7d1fbe0> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Locked ownable synchronize

我使用 this

分析线程转储

这是相同的屏幕截图。

我在我的应用程序中多次使用以下代码

ExecutorService executor = Executors.newFixedThreadPool(3);
//business logic
// This will make the executor accept no new threads and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {

}

ablow 代码会导致任何问题吗?

这个线程是高内存和 CPU 使用率的根本原因吗?

大量线程可能会导致内存问题,但如果所有线程都处于 WAITING 状态,则它们不会消耗处理器滴答。

我建议你一个一个解决你的问题。

要找出所有内存卡住的位置,您需要获取内存转储,并使用 MAT 等工具对其进行分析。

CPU消费问题可以通过SDK中的jconsolejvisualvm进行分析。他们都有分析器工具。

在我上面的代码中,我使用 while (!executor.isTerminated()){} 来等待所有任务完成他们的工作。此 while 循环使用 CPU 直到所有任务完成,这可能会导致高 CPU 问题。

我修改了我的代码如下。这解决了我的高 CPU 问题。

ExecutorService executor = Executors.newFixedThreadPool(3);
executor.shutdown();
executor.invokeAll(listOfTask);  // invokAll method will wait untill all task finished, No while loop here

了解更多信息read this