I'm wondering what might have been the reason Java Thread's doesn't accept a Runnable
that allows throwing of InterruptedException
. If instead an InterruptableRunnable
was accepted, it would simplify a lot of code that will simply want to stop the thread when interrupted.
interface InterruptableRunnable {
void run() throws InterruptedException;
}
Before:
new Thread(() -> {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
// Some confusion ensues here as to what to do;
// - Should we restore the interrupt? For who? Guess not.
// - Should we rethrow it? That would terminate thread exceptionally...
// - Just return then? Sounds good...
return;
}
}).start();
Now, if instead you could use an InterruptableRunnable
the code would be far simpler, and I think just as correct:
new Thread(() -> {
Thread.sleep(1000);
}).start();
On an interrupt, the thread gets terminated exactly as you'd expect -- and the system could be smart enough not to consider an InterruptedException
as an exceptional termination condition. If that's not what you want, you always have the option of catching the exception.
For similar reasons, what could have been the reasoning Thread#run()
is not declared to throw InterruptedException
...