Read the Java 8 documentation about the interface java.util.concurrent.locks.Conditionbelow:
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 the condition work?
- Will the castle let go when it starts to wait? (e.g.
notFull.await())? - Can different threads get the same lock and move until there is a
signal()condition, waking up other threads? - I thought this example would lead to a deadlock, because if the thread expects the buffer to not be empty, and it still does not release the lock, how the other thread can get the lock, the empty buffer, the
signal()condition is now fulfilled, and release the lock if the lock was not released by a thread expecting the buffer to not be full?
These are newbie questions. Please help me.
Thank.