I read concurency in practice. Now I want to understand how to handle InterrruptedException
Advices from book:
- Propagate the exception (possibly after some task-specific cleanup), making your method an interruptible blocking method, too; or
- Restore the interruption status so that code higher up on the call stack can deal with it.
- Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.
First two statements are clear for me but I don't understand third. Can you clarify this? Providing example will preferably.
update(thanks Shubham for the link )
The one time it is acceptable to swallow an interrupt is when you know the thread is about to exit. This scenario only occurs when the class calling the interruptible method is part of a Thread, not a Runnable or general-purpose library code, as illustrated in Listing 5. It creates a thread that enumerates prime numbers until it is interrupted and allows the thread to exit upon interruption. The prime-seeking loop checks for interruption in two places: once by polling the isInterrupted() method in the header of the while loop and once when it calls the blocking BlockingQueue.put() method.
public class PrimeProducer extends Thread {
private final BlockingQueue<BigInteger> queue;
PrimeProducer(BlockingQueue<BigInteger> queue) {
this.queue = queue;
}
public void run() {
try {
BigInteger p = BigInteger.ONE;
while (!Thread.currentThread().isInterrupted())
queue.put(p = p.nextProbablePrime());
} catch (InterruptedException consumed) {
/* Allow thread to exit */
}
}
public void cancel() { interrupt(); }
}
I don't understand the bolded text now.
PrimeProducer
is a good example of code which should swallow interruption. Whilst you might expect the code to be invoked directly as a thread, there is no reason only to use it like this: you could just use an instance of it anywhere that aRunnable
is to be used. As such, you don't know for certain that the thread is about to exit. The interrupted flag should be restored there; and where's the harm in doing so? It doesn't affect the "direct thread" use case, and fixes the "indirect" usage. – Relationship