img
. .
Thread 1 (The Consumer)
Thread 2 (The Stopper)
while (true) {
mutex.lock();
Thread.sleep(delay);
while (empty() & !stop) {
System.out.println("Stopping")
Thread.sleep(delay);
//
mutex.lock();
stop = true;
//
mutex.unlock();
consumerCV.condBroadcast();
producerCV.condBroadcast();
consumerCV.condWait(mutex);
}
if (stop)
break;
item = remove();
mutex.unlock();
producerCV.condSignal();
server.process(item);
}
InterruptedException
Exceptions are a wonderful mechanism to handle unusual situations. They allow you to write your
code in a simple, straightforward fashion and still be able to have special code for those special
situations. Moreover, should those special situations occur in many diverse locations in your code,
you are able to place a single exception handler at an appropriate location in your code, obviating
the need for large amounts of repeated code. Finally, because you can allow an exception to
propagate up through the call stack, it also provides you with a convenient method of executing
"indirect jumps" [by means of C's longjmp() or Lisp's catch/throw blocks].
This is fine when you intend to handle these exceptions, but what if you don't intend to handle
them? What about when you know there won't be any exceptions? What about
InterruptedException when you know you are never going to call interrupt()? Or
when you know you're simply going to ignore it?
So far, our code has been sprinkled with bits that look as shown in Code Example 7-11.
Example 7-11 Ignoring InterruptedException
try {
wait();
} catch (InterruptedException ie) {
}
The obvious alternative, propagating the InterruptedException up the call chain, is viable,
but a hassle. Just about every major method in your program will be propagating
InterruptedException, and should you be making lots of changes to your code, you'll be
inserting and removing "throws InterruptedException" regularly (Code Example 7-12).
What a pain for something that you won't be using.
Example 7-12 Propagating InterruptedException
public void foo() throws InterruptedException {
wait() or sleep() or read() etc.
}
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home