Java Reference
In-Depth Information
to stop, it will eventually notice the interrupt and stop, allowing the thread to terminate. But
another aspect of executing a task is that you want to find out if the task throws an excep-
tion. If
PrimeGenerator
throws an unchecked exception before the timeout expires, it
will probably go unnoticed, since the prime generator runs in a separate thread that does not
explicitly handle exceptions.
It runs the task in the calling thread and schedules a cancellation task to interrupt it after a
given time interval. This addresses the problem of unchecked exceptions thrown from the
task, since they can then be caught by the caller of
timedRun
.
This is an appealingly simple approach, but it violates the rules: you should know a thread's
interruption policy before interrupting it. Since
timedRun
can be called from an arbitrary
thread, it cannot know the calling thread's interruption policy. If the task completes before
the timeout, the cancellation task that interrupts the thread in which
timedRun
was called
could go off
after
timedRun
has returned to its caller. We don't know what code will be
running when that happens, but the result won't be good. (It is possible but surprisingly tricky
to eliminate this risk by using the
ScheduledFuture
returned by
schedule
to cancel
the cancellation task.)
Listing 7.8. Scheduling an Interrupt on a Borrowed Thread.
Don't do this.
Further, if the task is not responsive to interruption,
timedRun
will not return until the task
finishes, which may be long after the desired timeout (or even not at all). A timed run service
that doesn't return after the specified time is likely to be irritating to its callers.