Why is swallowing InterruptedException ok for subclasses of Thread?

前端 未结 3 1103
清歌不尽
清歌不尽 2021-01-13 07:31

In Brian Goetz\'s article on how to handle InterruptedException, one paragraph stands out:

The one time it\'s acceptable to swallow an interrupt is wh

3条回答
  •  醉酒成梦
    2021-01-13 08:03

    I agree with the others that the difference is whether you control that thread or not. If you extended a Thread, it's pretty much a given that you have control over that thread. On the other hand, if your code is simply a Runnable, it might be run on a borrowed thread (like from a thread pool) you do not own. By eating up the exception and not restoring the interrupt status, you deprive the code higher-up of the chance to recognize and act on the interruption.

    InterruptedException being a checked exception is, I think, a good thing. An InterruptedException is a way to request a cancellation of tasks. Suppose one wrote a task in the form of a Runnable that involves a blocking method that throws an InterruptedException. If it were not a checked exception, if you're not being careful you may not think to act on the InterruptedException (thus cancellation) and do your own clean-up.

    public class MyTask implements Runnable {
        public void run() {
            while (someCondition) {
                Object value = someBlockingQueue.take();
                // act on the value and loop back
            }
        }
    }
    

    Since InterruptedException is a checked exception, how my task should respond to interruption (cancellation) is front and center.

    public class MyTask implements Runnable {
        public void run() {
            while (someCondition) {
                try {
                    Object value = someBlockingQueue.take();
                    // act on the value and loop back
                } catch (InterruptedException e) {
                    // I'm being cancelled; abort
                    cleanUp();
                    // restore the interrupt
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }
    }
    

提交回复
热议问题