Domanda

Suppose I have two threads A and B, both running. Suddenly B decides to terminate A, and thus A should terminate ASAP. I don't want A to terminate instantly, but when it has reached a stable state.

A naive solution is to use a shared variable terminatePlease, which A would check for every time it reaches a stable state.

A prototype of the code looks like:

class A extends Thread {
    boolean terminatePlease;

    public void run() {
        while (true) {
            if (terminatePlease)
                return;
            doUninterruptableTasks();
        }
    }
}

Is there any other concurrency pattern to handle such situations?

È stato utile?

Soluzione

That's the idea, yes. The boolean should be volatile to make this solution work though.

But you don't even need this flag, because each thread has one already: the interrupted flag. So you could just call a.interrupt(); from thread B, and have your thread A do the following:

public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        doUninterruptableTasks();
    }
}

Note, though, that interrupting a thread blocked in a waiting state will make the blocking method throw an InterruptedException, in order to stop running ASAP. If you don't want that, then use a volatile flag.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top