简体   繁体   中英

Creating ThreadPoolExecutor in spring cause memory leak?

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());
}

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.

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 :

An unused ExecutorService should be shut down to allow reclamation of its resources.

Shut down the executor ( executor.shutdown() ), or reuse it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM