package com.millipad.util;

import java.util.Stack;

public class BlockingStack extends java.util.Stack {

	SharedLock lock;
	SharedLock limit;
	
	public BlockingStack() {
		lock = new SharedLock();
		limit = new SharedLock(0, Integer.MAX_VALUE);
		}

	public BlockingStack(int max) {
		lock = new SharedLock();
		limit = new SharedLock(0, max);
		}

	void debug(Object obj) {Debug.print(BlockingStack.class, obj);}

	public Object pop() {return pop(Long.MAX_VALUE);}

	public Object pop(long timeout) {
		try {
			int result = lock.acquireExclusive(timeout);
			if(result!=SharedLock.OKAY) return null;
			Object value = super.pop();
			limit.releaseExclusive();
			return value;
			}
		catch(InterruptedException e) {
			return null;
			}
		}

	public Object push(Object value) {return push(value, Long.MAX_VALUE);}

	public Object push(Object value, long timeout) {
		try {
			int result = limit.acquireExclusive(timeout);
			if(result!=SharedLock.OKAY) return null;
			super.push(value);
			lock.releaseExclusive();
			return value;
			}
		catch(InterruptedException e) {
			return null;
			}
		}

	}
