Java Reference
In-Depth Information
using interruption, so it is safe to set mayInterruptIfRunning when cancelling tasks
through their Future s when they are running in a standard Executor . You should not in-
terrupt a pool thread directly when attempting to cancel a task, because you won't know what
task is running when the interrupt request is delivered—do this only through the task's Fu-
ture . This is yet another reason to code tasks to treat interruption as a cancellation request:
then they can be cancelled through their Future s.
Listing 7.10 shows a version of timedRun that submits the task to an ExecutorService
and retrieves the result with a timed Future.get . If get terminates with a TimeoutEx-
ception , the task is cancelled via its Future . (To simplify coding, this version calls Fu-
ture.cancel unconditionally in a finally block, taking advantage of the fact that can-
celling a completed task has no effect.) If the underlying computation throws an exception
prior to cancellation, it is rethrown from timedRun , which is the most convenient way for
the caller to deal with the exception. Listing 7.10 also illustrates another good practice: can-
celling tasks whose result is no longer needed. (This technique was also used in Listing 6.13
on page 128 and Listing 6.16 on page 132 .)
Listing 7.10. Cancelling a Task Using Future .
Search WWH ::




Custom Search