Are Thread.stop and friends ever safe in Java?

前端 未结 8 1142
清酒与你
清酒与你 2020-11-28 08:05

The stop(), suspend(), and resume() in java.lang.Thread are deprecated because they are unsafe. The Oracle recommended w

8条回答
  •  半阙折子戏
    2020-11-28 08:38

    There is no safe way to kill a thread.

    Neither there is a subset of situations where it is safe. Even if it is working 100% while testing on Windows, it may corrupt JVM process memory under Solaris or leak thread resources under Linux.

    One should always remember that underneath the Java Thread there is a real, native, unsafe thread.

    That native thread works with native, low-level, data and control structures. Killing it may leave those native data structures in an invalid state, without a way to recover.

    There is no way for Java machine to take all possible consequences into account, as the thread may allocate/use resources not only within JVM process, but within the OS kernel as well.

    In other words, if native thread library doesn't provide a safe way to kill() a thread, Java cannot provide any guarantees better than that. And all known to me native implementations state that killing thread is a dangerous business.

提交回复
热议问题