img
. .
}
The most interesting piece of this code is where it deals with a race condition for interrupt().
Imagine that t1 has called t2.interrupt(). Soon afterward, t2 calls
disableInterrupts() with no intervening interruptible calls. That could leave the interrupt
flag set after disableInterrupts() returned. To prevent this, disableInterrupts()
checks for that condition, clears the flag [interrupted() does this automatically] and sets the
interruptPending flag so that a subsequent call to enableInterrupts() will notice this
and reissue the interrupt. Thus, the code following disableInterrupts() will never see an
interrupt and any interrupts issued previously to disableInterrupts() will not be lost.
A similar design could be used to disable thread.stop(), and indeed we do so in our
extensions package, but only as an illustration. It has been degradated -- don't use it.
A Cancellation Example (Improved)
Using the InterruptibleThread from above, we can now write a cleaner version of our
search program (Code Example 9-19). The two ugly portions of the program were
doDatabaseThing() and the cancellation code in searcher.run(). Using the
disable/enable code, the first function becomes simpler and the latter gets to eliminate all of its
checking code and simply call the interrupt() method with no further concerns.
Example 9-19 Cleaner Version of doDatabaseThing()
public void doDatabaseThing() {
try {
InterruptibleThread.disableInterrupts();
cancel.incrementDatabase(1);
Thread.sleep(10);
cancel.incrementDatabase(-1);
InterruptibleThread.enableInterrupts();
} catch (InterruptedException ie) {
InterruptibleThread.impossible(ie);
}
}
Simple Polling
In a program of any complexity, using cancellation is very difficult. A program that will be ported
to other languages will be even harder to write correctly. A strict polling scheme would be vastly
superior in almost every respect, as long as we don't have to worry about blocked threads. In the
code for CancellationNot (Code Example 9-20), we see the same searcher program written
using polling. (Note that where we test for cancel.found we could use double-checked
locking.)
Example 9-20 1Implementing the Searcher with Polling
public void run() {
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home