Proper way to handle Thread.interrupted() in a Callable? Proper way to handle Thread.interrupted() in a Callable? multithreading multithreading

Proper way to handle Thread.interrupted() in a Callable?


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 InterrutibleChannel classes. For example, reading from the following BufferedReader is interruptible and will throw InterruptedIOException. See here for more examples of the NIO code.

BufferedReader in = new BufferedReader(new InputStreamReader(    Channels.newInputStream((new FileInputStream(        new File(...))).getChannel())));

Then, you can call future.cancel() which will interrupt your thread and cause the IO to throw a InterruptedIOException. If that happens, you could not catch the IOException and let it trickle out of the call() method.


If you want to pass back to the Future that the call() method was interrupted then I think throwing InterruptedException is fine. Another option would be to just return null; or some other marker object from your call() method instead. That's typically what I do if a thread was interrupted.

One thing to remember is that if call() throws InterruptedException, when you do a future.get() it will throw a ExecutionException and the cause of that exception is going to be an InterruptedException. Don't be confused that future.get() can also throw a InterruptedException itself if the get(long timeout, TimeUnit unit) times out.

 try {     result = future.get(); } catch (ExecutionException e) {     if (e.getCause() instanceof InterruptedException) {        // call() method was interrupted     } } catch (InterruptedException e) {     // get was interrupted }

If, however, future.cancel(true) was called then the future.get() will throw a CancellationException instead.


It depends actually on how you want the thread waiting on get(). If you do not want the waiting thread to have an exception thrown then you do not want to throw new InterruptedException

Imagine

try{  future.get();}catch(ExecutionException ex){}catch(InterruptedException em){}

If any exception occurs what would you expect it to be? In your case it is an ExecutionException. If you do not want an ExecutionException then you should not rethrow the InterruptedException.