Note that there are some explanatory texts on larger screens.

plurals
  1. POWaiting on a condition in a reentrant lock
    text
    copied!<p>The following code is taken from the <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Condition.html" rel="noreferrer">JavaDoc of <code>Condition</code></a>:</p> <pre><code>class BoundedBuffer { 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(Object 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 Object take() throws InterruptedException { lock.lock(); try { while (count == 0) notEmpty.await(); Object x = items[takeptr]; if (++takeptr == items.length) takeptr = 0; --count; notFull.signal(); return x; } finally { lock.unlock(); } } } </code></pre> <p>Imagine 2 threads, <em>Consumer</em> and <em>Producer</em>, one using <code>take</code>, one <code>put</code> on a single instance of <code>BoundedBuffer</code>. </p> <p>Let's say <em>Consumer</em> goes first, runs <code>take()</code> in which he locks the <code>lock</code> and now loops on <code>notEmpty.await();</code>. </p> <p>How can now <em>Producer</em> possibly get into the <code>put()</code> method past locking the <code>lock</code>, which is already held by the <em>Consumer</em>?</p> <p>What am I missing here? Is the <code>lock</code> "temporarily released" while the thread is waiting on one of its conditions? And what does the <em>reentrancy</em> of the lock mean, exactly?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload