I am trying to understand what is the use of doing condition.await()
if I am already doing lock.lock()
If I understood locks correctly, once I do lock.lock()
it will not proceed any further if some other thread has a lock.
So, in this case if pushToStack()
has acquired a lock by doing lock.lock()
then what is the use of checking for stackEmptyCondition.await()
in the popFromStack()
method? Because anyway, the code will stop at the lock.lock() line in the popFromStack()
method. What am I missing/wrong?
public class ReentrantLockWithCondition {
Stack<String> stack = new Stack<>();
int CAPACITY = 5;
ReentrantLock lock = new ReentrantLock();
Condition stackEmptyCondition = lock.newCondition();
Condition stackFullCondition = lock.newCondition();
public void pushToStack(String item){
try {
lock.lock();
while(stack.size() == CAPACITY) {
stackFullCondition.await();
}
stack.push(item);
stackEmptyCondition.signalAll();
} finally {
lock.unlock();
}
}
public String popFromStack() {
try {
lock.lock(); // we are blocked here to acquire a lock
while(stack.size() == 0) {
stackEmptyCondition.await(); // then why do we need to check this again?
}
return stack.pop();
} finally {
stackFullCondition.signalAll();
lock.unlock();
}
}
}