Java Reference
In-Depth Information
When Future.get throws InterruptedException or TimeoutException and
you know that the result is no longer needed by the program, cancel the task with Fu-
ture.cancel .
7.1.6. Dealing with Non-interruptible Blocking
Many blocking library methods respond to interruption by returning early and throwing In-
terruptedException , which makes it easier to build tasks that are responsive to can-
cellation. However, not all blocking methods or blocking mechanisms are responsive to in-
terruption; if a thread is blocked performing synchronous socket I/O or waiting to acquire an
intrinsic lock, interruption has no effect other than setting the thread's interrupted status. We
can sometimes convince threads blocked in noninterruptible activities to stop by means sim-
ilar to interruption, but this requires greater awareness of why the thread is blocked.
Synchronous socket I/O in java.io. The common form of blocking I/O in server applic-
ations is reading or writing to a socket. Unfortunately, the read and write meth-
ods in InputStream and OutputStream are not responsive to interruption, but
closing the underlying socket makes any threads blocked in read or write throw a
SocketException .
Synchronous I/O in java.nio. Interrupting a thread waiting on an Interrupt-
ibleChannel causes it to throw ClosedByInterruptException and close
the channel (and also causes all other threads blocked on the channel to throw
ClosedByInterruptException ). Closing an InterruptibleChannel
causes threads blocked on channel operations to throw AsynchronousCloseEx-
ception . Most standard Channel s implement InterruptibleChannel .
Asynchronous I/O with Selector. If a thread is blocked in Selector.select (in
java.nio.channels ), wakeup causes it to return prematurely by throwing a
ClosedSelectorException .
Lock acquisition. If a thread is blocked waiting for an intrinsic lock, there is nothing
you can do to stop it short of ensuring that it eventually acquires the lock and makes
enough progress that you can get its attention some other way. However, the explicit
Lock classes offer the lockInterruptibly method, which allows you to wait
for a lock and still be responsive to interrupts—see Chapter 13 .
ReaderThread in Listing 7.11 shows a technique for encapsulating nonstandard cancella-
tion. ReaderThread manages a single socket connection, reading synchronously from the
Search WWH ::




Custom Search