When you shutdownNow your executor or call cancel(true) (by the way, shutdownNow already cancels already sent tasks, so your loop is not needed) your tasks are interrupted.
Depending on how they respond to the interrupt, they may:
- stop what they do immediately.
- stop what they do after a while because the interrupt signal is not checked regularly enough
- keep doing what they do because the interrupt signal was ignored
For example, if your tasks run a while(true) , you can replace it with something like:
while(!Thread.currentThread().isInterrupted()) {
Another example:
for (int i = 0; i < aBigNumber; i++) { if (Thread.currentThread().isInterrupted()) { break; } //rest of the code for the loop } cleanup(); //and exit
Another example, if you call a method that throws an InterruptedException:
try { Thread.sleep(forever); //or some blocking IO or file reading... } catch (InterruptedException e) { cleanup(); Thread.currentThread.interrupt(); //and exit }
source share