Are Thread.stop and friends ever safe in Java?

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

提交回复
热议问题