Hooli
Hooli

Reputation: 1195

executorservice not killing thread

Code:

//List all threads:
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
System.out.println(runningThreads.toString());

//Thread creation:
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(this);

//Thread termination:
executorService.shutdownNow();

//List all threads:
Set<Thread> runningThreads = Thread.getAllStackTraces().keySet();
System.out.println(runningThreads.toString());

I would expect the list that gets printed out to be exactly the same both times but what I'm getting is a print out of the thread that was created included in the results

How do I completely destroy a thread so that it's nowhere to be found?

Upvotes: 2

Views: 2969

Answers (1)

Jesper
Jesper

Reputation: 206776

shutdownNow() attempts to stop the running thread, but as its API documentation says:

This method does not wait for actively executing tasks to terminate. Use awaitTermination to do that.

So the thread may still be running when the code after the call to shutdownNow() returns. Note also that you need to make sure that the task running in the thread actually terminates; shutdownNow() is not going to kill the thread, it will just try to interrupt it.

As the documentation says, call executorService.awaitTermination(...) after calling shutdownNow() to wait until the thread has stopped.

Upvotes: 1

Related Questions