views:

63

answers:

1

In what situation would one want to pass false for the mayInterruptIfRunning parameter to Future.cancel()?

If I understand correctly, if you pass false and the task is cancelled but the thread is not interrupted, the result (or ExecutionException) will never be accessible because the task is still marked as cancelled (i.e. isCancelled() returns true and get() throws CancellationException.)

Other possible situations are:

  • The Runnable or Callable implementation does not check for interrupts and will run to completion even if you do interrupt it (here the interrupt makes no difference)
  • The task already completed before you called cancel() (again the interrupt makes no difference)
  • The task needs to perform some cleanup before it exits (a well-written implentation will use try ... finally for this.)
  • The task cannot terminate immediately and must continue to perform operations that would be affected by interrupts, e.g. blocking I/O (in this case you should probably not call cancel at all)

So when/why would you cancel a task without interrupting it?

+2  A: 

If you're afraid interrupting the task's execution might leave things in a bad state, and you simply want to mark it as canceled so that users of the Future will be aware of it (e.g. they should know the statistics requested weren't performed on time).

Writing threaded code that handles interrupts correctly is not trivial at all, and so one might simply prefer to avoid it.

Some information can be found here, here and of course in the great book Concurrent Programming in Java (by the guy who originally wrote java.util.concurrent).

abyx