Jim
Jim

Reputation: 19582

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?

Upvotes: 3

Views: 1856

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

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

Upvotes: 4

zch
zch

Reputation: 15278

It's not okay. You have to own monitor of the object to use its notFull.wait() method. Even if it was allowed it would still not release lock, so no other thread could access it.

Upvotes: 0

Ralf H
Ralf H

Reputation: 1474

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.

Upvotes: 1

Related Questions