1

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...

Deepak Agarwal
  • 907
  • 6
  • 21
  • 2
    Don't do that, basically. You should avoid terminating threads like this anyway - give your runnable a flag to check periodically. – Jon Skeet Mar 01 '14 at 16:44
  • You are right. But, is there anyway to terminate such thread without using its stop method. – Deepak Agarwal Mar 01 '14 at 16:47
  • 1
    If the thread isn't set up to allow cancellation (i.e. it's not looking to see if it is supposed to terminate), then the only way to stop it is to abort it. So, as Jon Skeet said, "don't do that." – Jim Mischel Mar 01 '14 at 16:51
  • Make it as a daemon thread. Then it will automatically end when the main thread exits. – Manu Viswam Mar 05 '14 at 09:23

1 Answers1

1

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()) {}
}
David Ehrmann
  • 7,366
  • 2
  • 31
  • 40