On 1/30/14 2:35 AM, David Holmes wrote:
On 30/01/2014 5:34 PM, Tristan Yan wrote:
Hi Stuart
I didn’t make my comment clear. You set interrupted as true when thread
gets interrupted. Here it's still going to wait until systemStub is not
null. Why do you still need interrupt current thread in this case.

Because the golden rule of interrupt handling is you either throw
InterruptedException or you re-assert the interrupted state. This allows code
further up the stack to respond to interrupts.

Right, thanks David.

While it's often acceptable to let InterruptedException propagate, or to catch and rethrow it, IE is a checked exception so this isn't always allowed. That's the case with this code. The only alternative in this case is to re-assert the interrupted state before returning.

There's some discussion of this in Goetz, et. al. "Java Concurrency In Practice", section 5.4. There's an example here of catching IE and reasserting the thread's interrupted state. Get this book if you don't have it already.

The *worst* thing to do is something like,

    try {
        ... wait or sleep or something that throws IE ...
    } catch (InterruptedException ie) {
        // ignored
    }

I write this all the time in toy programs, but product code and even test code should follow the golden rule.

s'marks

Reply via email to