Threads preserve class invariants when they are allowed to exit normally. Programmers often attempt to terminate threads abruptly when they believe the task is complete, the request has been canceled, or the program or JVM must shut down expeditiously.
...
Invoking Thread.stop()
results in the release of all locks a thread has acquired, potentially exposing the objects protected by those locks when those objects are in an inconsistent state. The thread might catch the ThreadDeath
exception and use a finally
block in an attempt to repair the inconsistent object or objects. However, this requires careful inspection of all synchronized methods and blocks because a ThreadDeath
exception can be thrown at any point during the thread's execution. Furthermore, code must be protected from ThreadDeath
exceptions that might occur while executing catch
or finally
blocks [Sun 1999]. Consequently, programs must not invoke Thread.stop()
.
...
However, the Thread.stop()
method causes the thread to stop what it is doing and throw a ThreadDeath
exception. All acquired locks are subsequently released [API 2006]. If the thread were in the process of adding a new integer to the vector when it was stopped, the vector would become accessible while it is in an inconsistent state. For example, this could result in Vector.size()
returning an incorrect element count because the element count is incremented after adding the element.
...
A thread may use interruption for performing tasks other than cancellation and shutdown. Consequently, a thread should be interrupted only when its interruption policy is known in advance. Failure to do so can result in failed interruption requests.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
THI05-J | low | probable | medium | P4 | L3 |
Related Guidelines
POS47-C. Do not use threads that can be canceled asynchronously | |
CWE-705. Incorrect Control Flow Scoping |
...
On Android, Thread.stop()
was deprecated in API level 1.
Bibliography
[API 2006] | Class |
[Sun 1999] |
|
24.3, Stopping a Thread | |
Concurrency Utilities, More information: Java Thread Primitive Deprecation | |
[JPL 2006] | 14.12.1, Don't Stop; 23.3.3, Shutdown Strategies |
2.4, Two Approaches to Stopping a Thread | |
Chapter 7, Cancellation and Shutdown |
...