Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do InterruptedExceptions clear a thread's interrupted status?

Tags:

If a thread is interrupted while inside Object.wait() or Thread.join(), it throws an InterruptedException, which resets the thread's interrupted status. I. e., if I have a loop like this inside a Runnable.run():

while (!this._workerThread.isInterrupted()) {
    // do something
    try {
        synchronized (this) {
            this.wait(this._waitPeriod);
        }
    } catch (InterruptedException e) {
        if (!this._isStopping()) {
            this._handleFault(e);
        }
    }
}

the thread will continue to run after calling interrupt(). This means I have to explicitly break out of the loop by checking for my own stop flag in the loop condition, rethrow the exception, or add a break.

Now, this is not exactly a problem, since this behaviour is well documented and doesn't prevent me from doing anything the way I want. However, I don't seem to understand the concept behind it: Why is a thread not considered interrupted anymore once the exception has been thrown? A similar behaviour also occurs if you get the interrupted status with interrupted() instead of isInterrupted(), then, too, the thread will only appear interrupted once.

Am I doing something unusual here? For example, is it more common to catch the InterruptedException outside the loop?

(Even though I'm not exactly a beginner, I tagged this "beginner", because it seems like a very basic question to me, looking at it.)

like image 488
Hanno Fietz Avatar asked Mar 26 '10 13:03

Hanno Fietz


1 Answers

The idea is that an interrupt should be handled once. If an explicit InterruptedException did not clear the "interrupt" flag then most catchers for InterruptedException would have to explicitly clear that flag. Conversely, you can "unclear" the flag by self-interruption (Thread.currentThread().interrupt()). Java's designers went for the semantics which would save keystrokes most of the time (i.e. you more often want to clear the flag than keep it set).

like image 190
Thomas Pornin Avatar answered Oct 31 '22 14:10

Thomas Pornin