0

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?

xingbin
  • 27,410
  • 9
  • 53
  • 103

1 Answers1

1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • After the request is finished, there are no references to `executor`, why did the threads and the `executor` not be garbage collected? – xingbin Apr 10 '18 at 17:14
  • because threads live outside the regular garbage collection lifecycle of the scope you're in. – Lucas Holt Apr 10 '18 at 17:16
  • @LucasHolt You mean the threads will keep exitsing in JVM after they have finished their jobs? – xingbin Apr 10 '18 at 17:25
  • @user6690200 not normal threads, but threads in a pool don't finish. When they've finished one task they wait for more. – Kayaman Apr 10 '18 at 17:28