Java newSingleThreadExecutor garbage collection Java newSingleThreadExecutor garbage collection multithreading multithreading

Java newSingleThreadExecutor garbage collection


I suppose the executor object will be garbage collected, but I do not know whether it will be also shutdown.

Actually Executors.newSingleThreadExecutor() under the wood creates a FinalizableDelegatedExecutorService instance which will call shutdown on finalize indicating that it will be shut down automatically when being garbage collected.

However, I don't believe that it is a good idea to rely on it too much as it is more an implementation detail that may change from one version to another, you should rather shut it down explicitly instead to prevent any unexpected bugs.


From the documentation of ExecutorService we can read

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

Basically, you will have to terminate the executor service manually. While the executor object in itself will be garbage collected, it's internal threads will not.


Objects can only be GC'd if that object is not referenced by a GC root. What is a GC root? The most common ones are System classes and a running thread. An ExecutorService will create and maintain running threads, so even though the ES is created within a method, the ES will still be reachable and not GC'd.

As others mention, you will need to shutdown the ES for it to be GC'd.