'How to stop a for loop inside an ExecutorService?
I've tried looking on other threads and I can't seem to find a proper answer,
When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them. I have no idea why it happens, but the most I've seen from other threads is that you should be using Thread.currentThread().isInterrupted() to check if it is interrupted, but adding a
if(Thread.currentThread().isInterrupted())
{return;}
Doesn't actually stop it all. I'm calling executor shutdownNow when a UI button is toggled off.
Code example:
executorService.submit(() -> {
ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
//Shit keeps going if you call ShutdownNow Todo
for (Rectangle rect : rects)
{
ctx.batzUtils.click(rect);
try
{
Thread.sleep(minDelayBetween, maxDelayBetween);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
});
Any ideas as to why or solutions would be greatly appreciated
Solution 1:[1]
Adding Thread.currentThread().interrupt() in my catch statement worked
Credit To @Sambit
Solution 2:[2]
When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.
This is a misleading statement. executorService.shutdownNow() cancels any jobs that have not run yet and interrupts all of the threads that are currently running. The reason why some of your threads aren't being interrupted is because you are catching InterruptedException in your for loop. Whenever InterruptedException is thrown, the interrupt bit of the running thread is cleared.
Whenever you catch InterruptedException, you should immediately re-interrupt the running thread so that the caller will know that the interrupt has been set. Your bug is a good example of why this pattern is necessary.
try {
Thread.sleep(minDelayBetween, maxDelayBetween);
} catch (InterruptedException e) {
// when InterruptedException is thrown it clears the interrupt bit so
// we need to re-interrupt the thread whenever we catch it
Thread.currentThread().interrupt();
// you should handle the interrupt appropriately and not just print it
return;
}
Here's a good tutorial on the subject of Java thread interrupts.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Batzpup |
| Solution 2 | Gray |
