Why do InterruptedExceptions clear a thread's interrupted status?
Posted
by Hanno Fietz
on Stack Overflow
See other posts from Stack Overflow
or by Hanno Fietz
Published on 2010-03-26T13:52:42Z
Indexed on
2010/03/26
14:03 UTC
Read the original article
Hit count: 271
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.)
© Stack Overflow or respective owner