我在 wildfly-9.0.1.Final
上运行的 java web 应用程序有时会消耗非常高的内存和 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 使用率高的根本原因吗?
最佳答案
在我上面的代码中,我使用了 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
关于java - java线程转储中的高线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46398942/