Brijendar Bakchodia
Brijendar Bakchodia

Reputation: 1797

Understanding giving up Lock within wait()

From the Java Condition Docs

class BoundedBuffer<E> {
   final Lock lock = new ReentrantLock();
   final Condition notFull  = lock.newCondition(); 
   final Condition notEmpty = lock.newCondition(); 

   final Object[] items = new Object[100];
   int putptr, takeptr, count;

   public void put(E x) throws InterruptedException {
     lock.lock();
     try {
       while (count == items.length)
         notFull.await();
       items[putptr] = x;
       if (++putptr == items.length) putptr = 0;
       ++count;
       notEmpty.signal();
     } finally {
       lock.unlock();
     }
   }

   public E take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0)
         notEmpty.await();
       E x = (E) items[takeptr];
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   }
 }

Suppose a thread Produce calls put and so Produce is now owning the lock lock. But the while condition is true so Produce does notFull.await(). My question is now if a thread Consume calls take, at the line which says lock.lock() what exactly happens?

I am kind of confused because we let the old lock go in the critical section and now need to acquire it from a different thread.

Upvotes: 1

Views: 55

Answers (1)

jeff
jeff

Reputation: 4333

If you look closer at the Javadoc for Condition.await(), you'll see that the await() method atomically releases the lock and suspends itself:

"The lock associated with this Condition is atomically released and the current thread becomes disabled for thread scheduling purposes and lies dormant until one of four things happens..."

Upvotes: 1

Related Questions