Conditions versus wait / notify objects
I've read about Condition
objects and how they offer multiple sets of wait for each object, and also allocates which object or group of objects / threads receive a particular signal.
Why Object
doesn't the ordinary one do it? For example.
Instead:
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
We doing this:
final Object notFull = new Object();
final Object notEmpty = new Object();
lock.lock();
try {
while (count == items.length)
notFull.wait();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.notify();
Don't we have multiple wait sets yet and differentiate among the notifiable threads?
source to share
In your example, you have created 2 conditions for one lock. This is what you cannot do with inline sync - you had to use 2 objects to get 2 conditions.
And your second code is broken because you didn't get a lock on notFull and notEmpty, but you call wait / notify - you get an IllegalMonitorStateException. But if you try to block both of them, you will see that you cannot do it at the same time. This difference
source to share