Reputation: 1595
The Java doc for shutdown() says:
shutdown
void shutdown()
Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.Invocation has no additional effect if already shut down. This method does not wait for previously submitted tasks to complete execution. Use awaitTermination to do that.
Aren't the two statements contradictory? (...previously submitted tasks are executed Vs does not wait for previously submitted tasks to complete execution) ?
I tried out a sample program with shutdown()
. And it does wait for previously submitted tasks to complete unlike shutdownNow()
!
Why the below code returns I have shutdown true
when it is supposed to wait for the factorial task to complete?
public class RunnableMain {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
RunnableFactorialTask runnableFactorialTask = new RunnableFactorialTask(5);
executor.submit(runnableFactorialTask);
executor.shutdown();
System.out.println(" I have shutdown.."+executor.isShutdown());
}
}
class RunnableFactorialTask implements Runnable {
private int num = 0;
public RunnableFactorialTask(int num) {
this.num = num;
}
@Override
public void run() {
int factorial = 1;
try {
Thread.currentThread().sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 2; i <= num; i++) {
factorial *= i;
}
System.out.println("factorial of :" + num + " =" + factorial);
}
}
Upvotes: 0
Views: 1125
Reputation: 9801
The calls to shutdownNow()
or shutdown()
are not blocking. That is what is referred to in the docs.
So if you call shutdown()
or shutdownNow()
, you get control back immediately, not only after everything has gracefully shut down. If you want to wait for all executors/threads to terminate after the call to shutdown[Now]()
, you have to call awaitTermination(...)
, which will block until everything is cleaned up. This is probably what you want. Also see answers to a similar question here: Difference between shutdown and shutdownNow of Executor Service
Upvotes: 5