img
. . . .
interrupt() on the current thread again, trusting that it will be seen in the caller's code
somewhere else.[4] This way, the exception will never be lost.
[4]
If the programmer doesn't deal with InterruptedException, what the heck is he doing
calling interrupt()?
Example 9-7 Calling interrupt() upon Return
public synchronized void lock() {
boolean interrupted = false;
while (owner != null) {
try {
wait();
} catch (InterruptedException ie) {
interrupted = true;
}
}
owner = Thread.currentThread();
if (interrupted)
owner.interrupt();
}
Of course, this code could block forever and that could be a problem. This is what the designer of
the program needs to deal with. He needs to guarantee that another thread will do whatever is
necessary to make this method return. (For a mutex or synchronized section, he must guarantee
that the owner releases it.)
So this is a good thing. We're not dropping interrupts. But we're still not out of the woods. What if
you have a method which calls one of these methods and that method doesn't know about you
reinterrupting? It could get nasty. Consider the naive code (shown in Code Example 9-8) for
condition variables and RWlocks.
What happens if we're blocked waiting to get a read lock and we get interrupted? Well, our
condition variable class doesn't want to throw InterruptedException, so it just schedules a
reinterrupt and returns as if from a spurious wakeup. Unfortunately, our lock code views the return
as spurious and just calls condWait() again. Which promptly sees the new interrupt and throws
InterruptedException again, etc. (Code Example 9-9). Don't do that.
So if we wanted to use that design for condition variables, we would need to keep that in mind and
play the same tricks in the readers/writer lock. Ugh!
Now, what we really want is for InterruptedException to work correctly and simply and
any synchronization variables we build on top of Java to be equally simple to use. By sticking
with our original version of condWait(), which doesn't treat InterruptedException as a
spurious wakeup, we get the best of both worlds (Code Example 9-10). This is also almost
certainly what you want to do in any of your code. If you want to get fancy, be careful!
Example 9-8 Naive Condition Variable and Readers/Writer Lock
public void condWait(Mutex mutex) {
boolean interrupted = false;
try {
synchronized (this) {
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home