Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditions vs objects wait/notify

I was reading about Condition objects and how they offer multiple wait-sets per object and also distinguishing which object or group of objects/threads get a specific signal.
Why doesn't a regular Object do that? E.g.

Instead of:

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 do 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 still have multiple wait-sets and distinguish among notified threads?

like image 928
Jim Avatar asked Jun 22 '26 21:06

Jim


2 Answers

In your example you created 2 Conditions on one Lock. This is what you can't do with built-in synchronization - you had to use 2 Objects to get 2 conditions.

And your second code is broken because you did not get lock on notFull and notEmpty but call wait / notify - you'll get IllegalMonitorStateException. But if you tried to lock them both you would see you cannot do that simultaneously. This is the difference

like image 78
Evgeniy Dorofeev Avatar answered Jun 24 '26 11:06

Evgeniy Dorofeev


You need to synchronize first when calling wait or notify. When you need two different sets, you need two objects to sync on. The nested sync will give you deadlocks.

like image 35
Ralf H Avatar answered Jun 24 '26 10:06

Ralf H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!