Reading the Java 8 documentation about the java.util.concurrent.locks.Condition
interface, the following example is given:
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();
}
}
}
So my main question is: How does a condition work?
notFull.await()
for example)?signal()
a condition, awaking other threads?signal()
the condition is now met, and release the lock if the lock hasn't been release by the thread waiting for the buffer to be not full?These are beginners questions. Please help me out.
Thank you.
await/signal/signalAll
has actually the same behavior as wait/notify/notifyAll
signal
or signalAll
, it releases respectively one thread or all threads awaiting for the corresponding Condition
such that the thread or those threads will be eligible to acquire the lock again. But for now the lock is still owned by the thread that called signal
or signalAll
until it releases explicitly the lock by calling lock.unlock
. Then the thread(s) that has/have been released will be able to try to acquire the lock again, the thread that could acquire the lock will be able to check the condition again (by condition this time I mean count == items.length
or count == 0
in this example), if it is ok it will proceed otherwise it will await
again and release the lock to make it available to another thread.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With