Java Reference
In-Depth Information
Listing 7.9 addresses the exception-handling problem of aSecondOfPrimes and the prob-
lems with the previous attempt. The thread created to run the task can have its own execution
policy, and even if the task doesn't respond to the interrupt, the timed run method can still
return to its caller. After starting the task thread, timedRun executes a timed join with
the newly created thread. After join returns, it checks if an exception was thrown from the
task and if so, rethrows it in the thread calling timedRun . The saved Throwable is shared
between the two threads, and so is declared volatile to safely publish it from the task
thread to the timedRun thread.
This version addresses the problems in the previous examples, but because it relies on a timed
join , it shares a deficiency with join : we don't know if control was returned because the
thread exited normally or because the join timed out. [2]
7.1.5. Cancellation Via Future
We've already used an abstraction for managing the lifecycle of a task, dealing with excep-
tions, and facilitating cancellation— Future . Following the general principle that it is better
to use existing library classes than to roll your own, let's build timedRun using Future
and the task execution framework.
Search WWH ::




Custom Search