Bastien
Bastien

Reputation: 658

Kill an infinite-loop thread in java

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()?

Upvotes: 1

Views: 3289

Answers (2)

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18148

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.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533502

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()

Upvotes: 1

Related Questions