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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With