java - question about thread abortion and deadlock - volatile keyword
        Posted  
        
            by Tiyoal
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Tiyoal
        
        
        
        Published on 2010-06-03T15:37:43Z
        Indexed on 
            2010/06/03
            16:24 UTC
        
        
        Read the original article
        Hit count: 270
        
Hello all,
I am having some troubles to understand how I have to stop a running thread. I'll try to explain it by example. Assume the following class:
public class MyThread extends Thread {
    protected volatile boolean running = true;
    public void run() {
        while (running) {
            synchronized (someObject) {
                while (someObject.someCondition() == false && running) {
                    try {
                        someObject.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // do something useful with someObject
            }
        }
    }
    public void halt() {
        running = false;
        interrupt();
    }
}
Assume the thread is running and the following statement is evaluated to true:
while (someObject.someCondition() == false && running)
Then, another thread calls MyThread.halt(). Eventhough this function sets 'running' to false (which is a volatile boolean) and interrupts the thread, the following statement is still executed:
someObject.wait();
We have a deadlock. The thread will never be halted.
Then I came up with this, but I am not sure if it is correct:
public class MyThread extends Thread {
    protected volatile boolean running = true;
    public void run() {
        while (running) {
            synchronized (someObject) {
                while (someObject.someCondition() == false && running) {
                    try {
                        someObject.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // do something useful with someObject
            }
        }
    }
    public void halt() {
        running = false;
        synchronized(someObject) {
            interrupt();
        }
    }
}
Is this correct? Is this the most common way to do this?
This seems like an obvious question, but I fail to come up with a solution. Thanks a lot for your help.
© Stack Overflow or respective owner