Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which code can swallow interruptedException?

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.

like image 327
gstackoverflow Avatar asked Feb 14 '17 06:02

gstackoverflow


1 Answers

Short answer: If you can deal with the situation, it is allowed to swallow it.

The interrupted exception occurs when the process occurring in that parallel thread was cancelled, or well, interrupted. So if you are the only one interested in that fact, and you can deal with the situation of having that thread "dead", then you can swallow it.

That is perfectly possible in real life examples. The strategy depends on each situation.

like image 153
Fernando Avatar answered Sep 28 '22 23:09

Fernando