A teammate made the following claim:
“
Thread.interrupt()is inherently broken, and should (almost) never be used”.
I am trying to understand why this is the case.
Is it a known best practice never to use Thread.interrupt()? Can you provide evidence why it is broken / buggy, and should not be used for writing robust multithreaded code?
Note – I am not interested in this question if it’s “pretty” from a design preservative. My question is – is it buggy?
Short version:
No.
The opposite is true: it is critical for multithreaded code.
See Listing 7.7 in Java Concurrency in Practice for an example.
Longer version:
Around here, we use this method in one specific place: handling
InterruptedExceptions. That may seem a little strange but here’s what it looks like in code:This does two things for us:
ie.printStackTrace();and a jaunty “TODO: Something useful needs to go here!” comment.throws InterruptedExceptionclause, this is your other option for propagating that interrupted status.A commenter suggested that I should be using an unchecked exception “to force the thread to die.” This is assuming that I have prior knowledge that killing the thread abruptly is the proper thing to do. I don’t.
To quote Brian Goetz from JCIP on the page before the listing cited above:
For example, imagine that I did this:
I would be declaring that, regardless of other obligations of the rest of the call stack and associated state, this thread needs to die right now. I would be trying to sneak past all the other catch blocks and state clean-up code to get straight to thread death. Worse, I would have consumed the thread’s interrupted status. Upstream logic would now have to deconstruct my exception to try to puzzle out whether there was a program logic error or whether I’m trying to hide a checked exception inside an obscuring wrapper.
For example, here’s what everyone else on the team would immediately have to do:
The interrupted state is more important than any specific
InterruptException. For a specific example why, see the javadoc for Thread.interrupt():As you can see, more than one InterruptedException could get created and handled as interrupt requests are processed but only if that interrupt status is preserved.