在春季创建ThreadPoolExecutor会导致内存泄漏? [英] Creating ThreadPoolExecutor in spring cause memory leak?
问题描述
我正在使用Spring,在RequestMap
方法中,我的代码如下:
I am working with Spring, and in a RequestMap
method I have code like below:
@RequestMap
public void someMethod() {
ThreadPoolExecutor executor = Executors.newFixedThreadPool(N);
executor.submit(new Runnable());
executor.submit(new Runnable());
}
然后,即使每一个Runnable
应该在几秒钟内完成,我仍然收到OOM错误.分析堆转储后,我发现有成千上万个Thread
对象.
Then I keep get OOM error even every Runnable
should be finished in seconds. After analysing the heap dump, I found there are thousands Thread
objects.
然后我用Executors.newCachedThreadPool
将executor
更改为singlton,此问题已解决.
Then I changed executor
to singlton with Executors.newCachedThreadPool
, this problem was fixed.
据我了解,该方法返回后,没有对线程池的引用,因此应该对其进行垃圾回收,但事实是线程仍在堆中.为什么?
As far as my understand, after the method returned, there is no reference to the thread pool, so it should be garbage-collected, but the fact is the thread still on the heap. Why?
推荐答案
是的,这将泄漏内存. 如文档中所述 :
Yes, this will leak memory. As it says in the documentation:
应关闭未使用的
ExecutorService
,以回收其资源.
An unused
ExecutorService
should be shut down to allow reclamation of its resources.
Shut down the executor (executor.shutdown()
), or reuse it.
这篇关于在春季创建ThreadPoolExecutor会导致内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!