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);
}
}