[concurrency-interest] Having TimeoutException be a subclass of InterruptedException

David Holmes dholmes@dltech.com.au
Fri, 6 Dec 2002 08:59:03 +1000

Luke Blanshard wrote:
> I have a question about having TimeoutException inherit
> from InterruptedException.  In the current JVM, an
> InterruptedException always means that the current thread
> has been interrupted.  I often keep track of this fact by
> setting a flag in the catch block for InterruptedException,
> and re-interrupting the thread when I've finished cleaning
> up after the interruption, so that outer or later code will
> also know that it is supposed to complete early.
> With this new subclass, you appear to have destroyed a
> useful invariant of the JVM.

The reasons for making TimeoutException extend InterruptedException

- logically a timeout can be considered an interrupt from a timer. It
could even be implemented this way under the covers - you couldn't
tell because the interrupt state is reset when the exception is thrown
- code that doesn't want to deal with normal or timer-based interrupts
can just declare that they throw a single exception -
InterruptedException - rather than two different checked exceptions.
Higher-level code doesn't need to know, and probably doesn't care
whether the interrupt was time-out related or not. (It would be
inconsistent for TimeoutException to not be a checked exception when
InterruptedException is).
- back in the old days (1.0/1.02/1.1) many people actually expected a
timeout from wait to throw InterruptedException :)

This doesn't break any existing code because the methods that can
throw TimeoutException are all new methods. To deal with the new
exception all you have to do is extend your current idiom with an
additional catch clause:

 try {
 catch(TimeoutException te) {
    // deal with timeout
 catch(InterruptedException ie) {
     // deal with general thread interruption

David Holmes