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?

+3


source to share


3 answers


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

+3


source


You must first synchronize

when calling wait

or notify

. When you need two different sets, you need two objects to sync. Nested sync will give you deadlocks.



+1


source


It is not normal. To use the method, notFull.wait()

you must own the object monitor. Even if allowed, it still won't free lock

, so no other thread will be able to access it.

0


source







All Articles