Are Thread.stop and friends ever safe in Java?

前端 未结 8 1125
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2020-11-28 08:44

    The lack of safety comes from the idea idea of critical sections

    Take mutex
    
    do some work, temporarily while we work our state is inconsistent
    
    // all consistent now
    
    Release mutex
    

    If you blow away the thread and it happend to be in a critical section then the object is left in an inconsistent state, that means not safely usable from that point.

    For it to be safe to kill the thread you need to understand the entire processing of whatever is being done in that thread, to know that there are no such critical sections in the code. If you are using library code, then you may not be able to see the source and know that it's safe. Even if it's safe today it may not be tomorrow.

    (Very contrived) Example of possible unsafety. We have a linked list, it's not cyclic. All the algorithms are really zippy because we know it's not cyclic. During our critical section we temporarily introduce a cycle. We then get blown away before we emerge from the critical section. Now all the algorithms using the list loop forever. No library author would do that surely! How do you know? You cannot assume that code you use is well written.

    In the example you point to, it's surely possible to write the requreid functionality in an interruptable way. More work, but possible to be safe.

    I'll take a flyer: there is no documented subset of Objects and methods that can be used in cancellable threads, because no library author wants to make the guarantees.

    0 讨论(0)
提交回复
热议问题