[3]
As a matter of fact, even this code is not flawless by the definition of interruption. It is
theoretically possible for the interrupter thread to get the lock, send an interrupt to the target thread,
and release the lock; the target thread could then lock the lock and Thread.interrupted()
could still return false. It's difficult to imagine an implementation of the JVM for which this could
happen, but it is possible according to the official definition.
Example 9-5 Testing a Variable from an Exception Handler
public synchronized boolean justInjured() {
if (health > 1)
return true;
else
return false;
}
public void attack() throws LiquidatedException {
...
try {
vaporizeDalique();
} catch (InterruptedException ie) {
if (justInjured())
synchronized (this) {
health--;
}
else {
// Eliminate Eliminate Eliminate
throw new LiquidatedException();
}
}
}
Ignore Interrupts
You could install interruption handlers that do nothing and assume that either the programmer will
never call interrupt or that she will keep calling it until the thread disappears. Most sample code
you see in other topics and articles does this. This is too much for a library to assume. Don't do
that.
Example 9-6 Inventing an InterruptDisabled Protocol
// The Interruptible Thread
public void doDatabaseThing() throws InterruptedException {
InterruptibleThread t = InterruptibleThread.self();
synchronized (t) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
t.inCriticalSection = true; // Don't cancel in critical
section!
}
try {
incrementDatabase(1);
Thread.sleep(10);
// Or some other interruptible
method
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home