C produced by producer.
C consumed by consumer.
D produced by producer.
D consumed by consumer.
Caution Never call wait() outside of a loop. The loop tests the condition
( !writeable or writeable inthepreviousexample)beforeandafterthe wait()
call.Testingtheconditionbeforecalling wait() ensures liveness .Ifthistestwasnot
present,andiftheconditionheldand notify() hadbeencalledpriorto wait() be-
ditionaftercalling wait() ensures safety .Ifretestingdidnotoccur,andifthecondi-
tiondidnotholdafterthethreadhadawakenedfromthe wait() call(perhapsanoth-
erthreadcalled notify() accidentally whenthecondition didnothold),thethread
would proceed to destroy the lock's protected invariants.
thelocktothatcriticalsection. Listing4-28 'satypicalexampledemonstratesthisscen-
ario, which is known as deadlock .
Listing 4-28. A pathological case of deadlock
private Object lock1 = new Object();
private Object lock2 = new Object();
// critical section guarded first by
// lock1 and then by lock2