Java Reference
In-Depth Information
Restore the interrupt.
Sometimes you cannot throw
InterruptedException
, for
instance when your code is part of a
Runnable
. In these situations, you must catch
InterruptedException
and restore the interrupted status by calling
inter-
rupt
on the current thread, so that code higher up the call stack can see that an inter-
rupt was issued, as demonstrated in
Listing 5.10
.
You can get much more sophisticated with interruption, but these two approaches should
work in the vast majority of situations. But there is one thing you should
not
do with
In-
terruptedException
—catch it and do nothing in response. This deprives code higher
up on the call stack of the opportunity to act on the interruption, because the evidence that
the thread was interrupted is lost.
The only situation in which it is acceptable to swallow an
interrupt is when you are extending Thread and therefore control all the code higher up on
Listing 5.10. Restoring the Interrupted Status so as Not to Swallow the Interrupt.
5.5. Synchronizers
Blocking queues are unique among the collections classes: not only do they act as containers
for objects, but they can also coordinate the control flow of producer and consumer threads
because
take
and
put
block until the queue enters the desired state (not empty or not full).