package com.millipad.util;

import java.util.Stack;

public class BlockingQueue {

        BlockingStack in, out;
        
	public BlockingQueue() {
            in = new BlockingStack();
            out = new BlockingStack();
	}

	public BlockingQueue(int max) {
            in = new BlockingStack(max);
            out = new BlockingStack(max);
	}

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

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

	public Object pop(long timeout) {
            return out.pop(timeout);
        }

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

        public synchronized Object push(Object value, long timeout) {
            for(;;) {
                Object tmp = out.pop(1);
                if(tmp==null) break;
                in.push(tmp, timeout);
            }
            Object result = in.push(value, timeout);
            for(;;) {
                Object tmp = in.pop(1);
                if(tmp==null) break;
                out.push(tmp, timeout);
            }
            return result;
        }

        public int size() {
            return out.size();
        }
        public static void main(String[] arg) {
            BlockingQueue q = new BlockingQueue();
            System.out.println(q.pop(1000));
            q.push(new Object());
            System.out.println(q.pop(1000));
            q.push(new Object());
            System.out.println(q.pop(1000));
        }
}
