ichfarbstift ichfarbstift - 2 months ago 19
Java Question

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?

Answer

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.

Comments