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?
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
.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With