I just want to train before interview. I googled concurrency interview questions and one of the question was write concurrent ready stack.
public interface ConcurrentStack<T> {
void put(T t) throws InterruptedException;
T poll() throws InterruptedException;
}
class BlockingConcurrentStack<T> implements ConcurrentStack<T> {
private List<T> list = new ArrayList<>();
private int maxSize;
public BlockingConcurrentStack(int maxSize) {
this.maxSize = maxSize;
}
@Override
public synchronized void put(T t) throws InterruptedException {
while (maxSize <= list.size()) {
wait();
}
list.add(t);
notify();
}
@Override
public synchronized T poll() throws InterruptedException {
while (list.size() == 0) {
wait();
}
T t = list.get(list.size() - 1);
list.remove(t);
notify();
return t;
}
}
poll()to have timeout and to returnnullif there is nothing to pull out from the collection but your implementation has not. To be consistent with other concurrent collections I'd call ittake()instead. \$\endgroup\$put()andpoll()which should be renamedtake()) while often a non-blocking throwing/ method is useful, I'd then add bothadd()andpoll(). I'd even go a step further and I'd implement all the other useful methods (likeoffer()andpeek()) but it's probably just over-engineering at this stage. \$\endgroup\$ConcurrentStack<T>andCollection<T>. \$\endgroup\$