Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecutorService shutdown

I am confused about the javadoc of ExecutorService#shutdown method. Aren't these contradictory statements?

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted. This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.

If it can orderly shutdown previously submitted tasks, then how can't it wait for them to complete execution?

like image 781
ParagJ Avatar asked Apr 18 '13 11:04

ParagJ


2 Answers

It means that the method returns immediately in the thread that you call it in, but tasks that haven't yet been executed might still be running, in other threads.

If you want your program to wait until the tasks that had been submitted previously have finished, you have to call awaitTermination after calling shutdown.

like image 123
Jesper Avatar answered Oct 11 '22 07:10

Jesper


It means that the tasks will run to completion, but this method will return immediately, without waiting for that to happen.

So, to cleanly shutdown your executor without killing any tasks, you would do:

executor.shutdown();
executor.awaitTermination(long timeout, TimeUnit unit);

Alternatively, if you just want to stop your executor as quickly as possible, use shutdownNow().

like image 40
Chris B Avatar answered Oct 11 '22 07:10

Chris B