Implement a multi-threaded stack, with freedom to use existing implementations of stack. On top of being thread-safe, it must block (not busy-wait) a pushing thread when stack is full and a popping thread when stack is empty. It must signal the threads out of sleep when stack has space again or elements to pop. Fairness is optional in this question.
How can I implement such a stack in Java? I came up with below implementation. Is this the correct way to solve above problem?
public class MyStack<E> {
private final Stack<E> stack;
private int max = 16;
private final ReentrantLock lock = new ReentrantLock(true);
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
public MyStack(int size) {
this.stack = new Stack<>();
this.max = size;
}
public void push(E e) {
lock.lock();
try {
while (stack.size() == max) {
notFull.await();
}
stack.push(e);
notEmpty.signalAll();
} catch (InterruptedException e1) {
e1.printStackTrace();
} finally {
lock.unlock();
}
}
public E pop() {
lock.lock();
try {
while (stack.size() == 0) {
notEmpty.await();
}
E item = stack.pop();
notFull.signalAll();
return item;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
Stack
ajava.util.Stack
? Isn'tjava.util.Stack
already thread-safe? \$\endgroup\$