One of my Runnable runs following code:
while(true) {}
I have tried wrapping that Runnable in Executor apis and then tried shutdown method. Tried thread.interrupt. but nothing works. I can not modify Runnable code. Any suggestions...
One of my Runnable runs following code:
while(true) {}
I have tried wrapping that Runnable in Executor apis and then tried shutdown method. Tried thread.interrupt. but nothing works. I can not modify Runnable code. Any suggestions...
Check its interrupted flag:
while (!Thread.currentThread().isInterrupted()) {}
Most of the Executors interrupt worker threads on shutdownNow
, so this gives you a tidy mechanism for a clean shutdown.
If you need to terminate the Runnable
outside the context of an Executor
, you'll need to give it a shutdown
method that sets a flag.
final AtomicBoolean isShutdown = new AtomicBoolean();
public void shutdown() {
if (!isShutdown.compareAndSet(false, true)) {
throw new IllegalStateException();
}
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted() && !isShutdown.get()) {}
}