1

Is there any way I can stop a thread without using deprecated stop()?

The thread invokes some methods from a potentially badly written class which may contain infinite loops. Since I can't modify this class, I have no control over the loop condition and therefore can't exit normally using interrupt() or any other variable. Is it justified in this case to use stop()?

Bastien
  • 658
  • 1
  • 9
  • 24
  • Keep in mind that even `stop` doesn't guarantee your rogue thread will stop. A simple `try {...} catch (Throwable t) {}` will make the thread unstoppable. – Marko Topolnik Aug 03 '13 at 16:02
  • I'm lost here. How come a try/catch will prevent me to stop a thread? – Bastien Aug 03 '13 at 16:58
  • `stop` doesn't do anything more than throw an exception in the thread. The semantics of exception handling are unchanged. Try it for yourself: `Thread t = new Thread() { public void run() { for (;;) try { System.out.println("Still running"); Thread.sleep(100); } catch (Throwable t) {} } }; t.start(); t.stop(); ` – Marko Topolnik Aug 03 '13 at 17:07

2 Answers2

1

If you cannot use stop() and cannot fix the code, your only other option is to run the code in another process and kill the process.

In your case, the simplest option is to use Thread.stop()

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I thought that if a thread does not respond to interrupt it does not respond to stop either... – assylias Aug 03 '13 at 18:38
  • 1
    @assylias stop() triggers a ThreadDeath error, or any Throwable you provide. While a thread can catch this and ignore it, this is relatively unusual, esp compared with not checking the interrupt() – Peter Lawrey Aug 03 '13 at 19:13
0

The problem with the stop() method is that it can leave synchronized objects in an inconsistent state (i.e. if you stop the thread while you're halfway through a synchronized object update, then only part of the object may be updated). If your thread isn't using any synchronized methods / blocks then it's safe to stop it.

If your thread might be using a synchronized block/method, then try to cleanly shut it down before calling stop, e.g. call interrupt on it and then call stop X minutes later if the thread still hasn't stopped (operating on the assumption that the thread is calling a broken method). Just be sure that the thread leaves everything in a consistent state before calling a potentially broken method.

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
  • 2
    The problems with `stop` are not just about synchronized blocks, you are just reiterating what you have read elsewhere. The problem is that an exception can appear at any point of code, even at `int i = 1;` and most code is not ready to handle that: it makes assumptions about where exceptions can and can't occur. A repeated `stop` can then break the handler code, and so on. – Marko Topolnik Aug 03 '13 at 16:52