Search code examples
javathread-safetyvolatile

Thread stop and synchronization


I'm reading a book which says not to use such a code:

private volatile Thread myThread;

....

myThread.stop();

Instead one should use:

if (myThread != null ) {

 Thread dummy = myThread;

 myThread = null;

 dummy.interrupt();


}

Unfortunately the subject is not elaborated any further... Could someone explain me this?


Solution

  • Everyone has given great information on why not to call Thread.stop().

    Sergey's comment fixed the incorrect information I gave about interrupt() handling. I prefer to use a signal flag, like in lewap's answer. Like Sergey's said, interrupt() is for the purpose of waking up a thread that's in a blocked operation. If your thread doesn't call any blocking operations, then interrupt() won't actually terminate the thread. Your thread though can call isInterrupted() to see if interrupt has been called (a signal flag, basically).

    Going back to your book's example, I don't like it.

    if (myThread != null ) {
    
        Thread dummy = myThread;
    
        myThread = null;
    
        dummy.interrupt();
    
    }
    

    There's no good reason to copy to a dummy variable in this example. You are right to be confused.

    The book authors might be thinking about trying to prevent other threads from simultaneously attempting to interrupt the same thread, but that interruption code is not thread safe (the "check if null and set to null" operation is not atomic), so writing the dummy assignment is muddying the waters without adding actual thread safety.