Java Reference
In-Depth Information
socket and passing any data received to processBuffer . To facilitate terminating a user
connection or shutting down the server, ReaderThread overrides interrupt to both
deliver a standard interrupt and close the underlying socket; thus interrupting a Reader-
Thread makes it stop what it is doing whether it is blocked in read or in an interruptible
blocking method.
7.1.7. Encapsulating Nonstandard Cancellation with Newtaskfor
The technique used in ReaderThread to encapsulate nonstandard cancellation can be re-
fined using the newTaskFor hook added to ThreadPoolExecutor in Java 6. When a
Callable is submitted to an ExecutorService , submit returns a Future that can
be used to cancel the task. The newTaskFor hook is a factory method that creates the Fu-
ture representing the task. It returns a RunnableFuture , an interface that extends both
Future and Runnable (and is implemented by FutureTask ).
Customizing the task Future allows you to override Future.cancel . Custom cancel-
lation code can perform logging or gather statistics on cancellation, and can also be used to
cancel activities that are not responsive to interruption. ReaderThread encapsulates can-
cellation of socket-using threads by overriding interrupt ; the same can be done for tasks
by overriding Future.cancel .
CancellableTask in Listing 7.12 defines a CancellableTask interface that extends
Callable and adds a cancel method and a newTask factory method for constructing
a RunnableFuture . CancellingExecutor extends ThreadPoolExecutor , and
overrides newTaskFor to let a CancellableTask create its own Future .
Search WWH ::




Custom Search