Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent the ThreadDeath error in java?

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?

like image 298
BendedWills Avatar asked May 11 '26 16:05

BendedWills


1 Answers

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.

Thread.stop() - deprecated

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.

like image 77
Plee Avatar answered May 14 '26 08:05

Plee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!