Figure 6-11. Extra Contention: When the Mutex Is Held by a Different Thread
InterruptedException
Now we need to deal with a little detail. For reasons we'll go into later (see Defined
InterruptedException. One of those methods is object.wait(), another is
Thread.sleep(). We don't want to do anything with it yet, so we'll simply include a try/ catch
block and ignore it. Our code is shown in Code Example 6-16. In production code you should
never ignore any exceptions.
Example 6-16 Using wait/notify with InterruptedException
try {
synchronized (object) {
while (!object.my_condition)
object.wait();
}
} catch (InterruptedException(e) {}
// Ignore for now
Controlling the Queue Length
So how do we prevent the queue from growing in the producer/ consumer example? The simplest
way is to initialize a second semaphore to the maximum allowed length and count it down.[12] This
works quite well for simple programs, but you will probably never actually use this in a
production program.
[12]
One way to imagine this inverse use of a semaphore is to consider the queue to have some
number of slots available. The semaphore encodes this number. When a producer places a new
Search WWH :