Brandon
Brandon

Reputation: 23498

Abrupt termination of threads

In C and C++, when you call TerminateThread (Windows) or pthread_kill (Linux), it can leak allocated resource which were not freed before such an abrupt thread death. These are the OS specific calls for terminating a thread by force. Destructors in C++ are not called when this happens.

Can and does the same thing happen in Java when you call Thread.stop()? Does the JVM collect all objects allocated within the life time of the thread right before the abrupt termination of said thread? OR does it leak as well?

Upvotes: 0

Views: 318

Answers (2)

Francis Au
Francis Au

Reputation: 56

Check this page for Java 8 http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

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.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272237

When the JVM terminates a thread, the corresponding stack and references will be cleared, and consequently the objects referred to exclusively by those references will be candidates for garbage collection.

Thread.stop() is deprecated, and you shouldn't call it. From the doc:

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

so it's not to do with resource allocation issues, but object integrity.

Upvotes: 3

Related Questions