I am in the creation of a 2d game, and when I try to stop a Thread, it suspends itself and throws a ThreadDeath error.
For some reason, this only happens in debug mode.
How can I catch this error, or prevent it?
I am in the creation of a 2d game, and when I try to stop a Thread, it suspends itself and throws a ThreadDeath error.
For some reason, this only happens in debug mode.
How can I catch this error, or prevent it?
ThreadDeath error is thrown when Thread.stop() is called. Thread.stop() is deprecated and should be avoided as it is unsafe.
Why is Thread.stop deprecated? Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked. (The monitors are unlocked as the ThreadDeath exception propagates up the stack.) If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged. When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect, or it may be pronounced. Unlike other unchecked exceptions, ThreadDeath kills threads silently; thus, the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.
Best way to stop a thread is to let the Thread terminate itself naturally. For example if you have a thread that monitors your application's state using a while loop, you can use have a running field in your thread and set it to false from the main loop to allow the Thread to terminate itself gracefully.