a-u
a-u

Reputation: 31

What is the exit strategy for Executors.newSingleThreadExecutor()

I'm new to java concurrency so this may be a question already answered many time over or too obvious that I maybe missing something.

I am running as task like so:

Executors.newSingleThreadExecutor().execute(task)

My question is when its comes to end of executing the run method of task why does it not exit or why is the thread still alive? My understanding was once a threads run() completes the thread is no more and ceases to exist, right?

Upvotes: 3

Views: 5786

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499740

newSingleThreadExecutor returns an ExecutorService which uses a single thread - it can still execute multiple tasks. It doesn't exit because you may want to supply more tasks.

You can use:

ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(task);
service.shutdown();

to shut it down after the task has executed.

Upvotes: 7

Francisco Meza
Francisco Meza

Reputation: 883

the thread remains alive because its lifecycle is not tied to that of the tasks assigned to the executor; take a look at:

javadoc for Executors.newSingleThreadExecutor

you'll find that internally, the returned ExecutorService uses a single thread to sequentially run as many tasks as you assign to it, potentially instantiating a new thread if one of your tasks kills the original one.

Upvotes: 3

Related Questions