Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java newSingleThreadExecutor garbage collection

Consider the following Java code

void doSomething(Runnable r1, Runnable r2){
  Executor executor = Executors.newSingleThreadExecutor();
  executor.execute(r1);
  executor.execute(r2);
}

when I invoke the doSomething method, the executor is created and performs the tasks r1 and r2 sequentially one after the other.

My question is: what happens once the two tasks r1 and r2 terminate?

I suppose the executor object will be garbage collected, but I do not know whether it will be also shutdown. If the executor creates a new thread for its execution, will this thread result in a resource leak?

like image 709
ichfarbstift Avatar asked Sep 29 '16 14:09

ichfarbstift


2 Answers

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.

like image 62
Nicolas Filotto Avatar answered Oct 14 '22 11:10

Nicolas Filotto


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.

like image 25
Gikkman Avatar answered Oct 14 '22 13:10

Gikkman