How can I write idiomatic code that is potentially used in a Thread
and thus needs/should support interruption?
Thread.close()
is deprecated. My understanding is, that any code that might be relied on from within a thread consequently needs to support/check the interrupt() flag of the Thread
object to allow the thread creator to stop a thread proper at a time of their choosing. However, it seems rather silly and non idiomatic to write code such as:
def interruptibleFunction() {
doSmth()
if (Thread.interrupted())
throw new InterruptedException();
doSmth()
if (Thread.interrupted())
throw new InterruptedException();
doSmth()
if (Thread.interrupted())
throw new InterruptedException();
//... and so on and so forth
}
I want my code to terminate as soon as (or as timely as possible as) the corresponding thread has been interrupted/is supposed to stop. Each of the doSmth()
might take a long time, which could be the actual reason for the interrupt in the first place. Consequently, it would be rather rude by the function to proceed even if an interrupt has been called.
Is this the only way to write interruptible code or is there another more idiomatic way?