When I am running a main thread as in a public static void main
method, the thread terminates when the method completes. I don't do anything explicit to shutdown the thread.
Why then in case of ExecutorService
. we have a shutdown() method? Why cannot we just let the thread(s) managed by ExecutorService
run to completion?
Asked
Active
Viewed 70 times
0

Victor
- 16,609
- 71
- 229
- 409
1 Answers
0
The invocation of shutdown method just means that no new tasks will be accepted by the executor. You can give a timeout to the running tasks(to run to completion) submitted to the executor.
executor.shutdown();
try {
//blocks until all tasks have finished or timeout occurs
executor.awaitTermination(TimeUnit.MICROSECONDS , Long.MAX_VALUE);
} catch (InterruptedException e) {
//Take some action at least Thread.currentThread().interrupt();
}

bsd
- 2,707
- 1
- 17
- 24
-
So the shutdown methods will not terminate all the worker threads in the pool? – Victor Jul 27 '13 at 16:08
-
Also can you explain why you did:Thread.currentThread().interrupt()... why are you sending an Interuupt inside an InterruptedException? – Victor Jul 27 '13 at 16:10
-
No, they will stop accepting tasks by throwing `RejectedExecutionException`. The interrupt part is already discussed - Don't swallow interrupts(http://stackoverflow.com/questions/4906799/why-invoke-thread-currentthread-interrupt-when-catch-any-interruptexception) – bsd Jul 27 '13 at 16:13