neham
neham

Reputation: 341

Does Executors.newSingleThreadExecutor service needs a cleanup using shutdown?

I have one slight confusion regarding clean up of executor service using newSingleThreadExecutor. As per its implementation, it internally creates a thread pool of one thread and in case of failure a new one will be created. And I am using singleThreadExecutor as I want to sequentially run the tasks created at runtime. So my concern is do I need to shutdown this executor service, when there are no more tasks in the system?

I have read that the active threads inside the ExecutorService prevents the JVM from shutting down. Since singleThreadExecutor also creates a thread pool inside, so does that mean that the thread is active or not?

Sorry if there is already question about it.

Upvotes: 4

Views: 4568

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533442

it internally creates a thread pool of one thread

Correct

in case of failure a new one will be created

It traps all Throwable so it doesn't fail when you get an error in the first place.

So my concern is do I need to shutdown this executor service, when there are no more tasks in the system?

You should shutdown is you are worried about resources. If you thread is a daemon thread it won't prevent the JVM from shutting down (by default it will be a non-daemon thread.

I have read that the active threads inside the ExecutorService prevents the JVM from shutting down.

Only non-daemon thread prevent the JVM from shutdown.

Since singleThreadExecutor also creates a thread pool inside, so does that mean that the thread is active or not?

It will be active when it is working on something. Whether it is active or not doesn't change whether the JVM is shutdown or not, only whether the thread is a daemon or not.

You can make the thread a daemon thread by providing thread factory. I suggest you do this even if all you do is set the name as this make debugging/profiling your application easier.

Here is an example I wrote earlier NamedThreadFactory

Upvotes: 3

Related Questions