What is the proper way to handle Thread.interrupted() in a Callable? I’m guessing that the callable should throw an InterruptedException; for example:
public class MyCallable implements Callable<Object> {
public Object call() {
Object result = null;
// Simulate long-running operation that calculates result
while (true) {
...
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
result = ... // something produced by the long-running operation
return result;
}
}
Is this correct, or is there a more appropriate way to handle it? Thanks.
Edit:
After some back and forth, it seems like you want to be able to interrupt your IO routines. This seems like a good job for some of the NIO
InterrutibleChannelclasses. For example, reading from the followingBufferedReaderis interruptible and will throwInterruptedIOException. See here for more examples of the NIO code.Then, you can call
future.cancel()which will interrupt your thread and cause the IO to throw aInterruptedIOException. If that happens, you could not catch theIOExceptionand let it trickle out of thecall()method.If you want to pass back to the
Futurethat thecall()method was interrupted then I think throwingInterruptedExceptionis fine. Another option would be to justreturn null;or some other marker object from yourcall()method instead. That’s typically what I do if a thread was interrupted.One thing to remember is that if
call()throwsInterruptedException, when you do afuture.get()it will throw aExecutionExceptionand the cause of that exception is going to be anInterruptedException. Don’t be confused thatfuture.get()can also throw aInterruptedExceptionitself if theget(long timeout, TimeUnit unit)times out.If, however,
future.cancel(true)was called then thefuture.get()will throw aCancellationExceptioninstead.