3

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?

Jim
  • 18,826
  • 34
  • 135
  • 254

3 Answers3

3

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • So it is just "saving" no of objects? – Jim Feb 12 '13 at 12:46
  • No, it's avoiding the deadlock caused by having to acquire two different monitors in the nested synchronized blocks. – Ralf H Feb 12 '13 at 12:48
  • @RalfH:`deadlock in nested synchronized`. Would it be possible to give an example of this? – Jim Feb 12 '13 at 12:59
  • @Jim Something like http://stackoverflow.com/questions/10365132/java-nested-synchronization-blocks ? – Ralf H Feb 12 '13 at 13:41
1

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.

Ralf H
  • 1,392
  • 1
  • 9
  • 17
  • But with condition I would still need to `Condition` objects – Jim Feb 12 '13 at 12:36
  • 1
    Two conditions is OK, as long as you have to lock one lock object only, not two different locks. This is what you can't do with monitors. – Ralf H Feb 12 '13 at 12:47
  • There is quite a lot of Q&A on this topic here. See http://stackoverflow.com/questions/3190545/java-wait-notify-and-synchronized-blocks and http://stackoverflow.com/questions/2779484/why-wait-should-always-be-in-synchronized-block, for eaxmple. – Ralf H Feb 12 '13 at 13:35
0

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.

zch
  • 14,931
  • 2
  • 41
  • 49