The same buffer with ReentrantLock and two Conditions
Threads often need to wait for something (an item in a queue, free space, a signal). The built-in way is wait/notifyAll on a synchronized object; since Java 5, ReentrantLock with Condition does the same with more control: timeouts, interruptible waiting, fairness and several separate wait queues.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Rewrite the bakery example using ArrayBlockingQueue instead of hand-written wait/notify.
Explain it without notes
Why must wait be called in a loop?
When would you choose ReentrantLock over synchronized?
What is the advantage of two Conditions over one notifyAll?
Expected output
sum of 1..100 passed through a 2-slot buffer: 5050