package ws.prova;

/*
 * Copyright (C) 2002-2007 <a href="mailto:a.kozlenkov@city.ac.uk">Alex Kozlenkov</a>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.util.Vector;

/**
 * TaskQueue class for processing Task(s)
 * <p>Title: Prova</p>
 * <p>Description: TaskQueue class for processing Task(s)</p>
 * <p>Copyright: Copyright (C) 2002-2007</p>
 * <p>Company: City University, London, United Kingdom </p>
 *
 * @author Alex Kozlenkov
 * @version 2.0 <25 March 2007>
 */

public class ResultQueue implements IResultQueue {
	private Vector results = new Vector();
	private boolean waiting;
	private boolean shutdown;

	public void setShutdown(boolean isShutdown) {
		shutdown = isShutdown;
		synchronized (this) {
//			System.out.println("Shutdown call.");
			notifyAll();
		}
	}

	public ResultQueue() {
		results = new Vector();
		waiting = false;
	}

	public void put(Object r) {
		results.add(r);
		if (waiting) {
			synchronized (this) {
				if( !results.isEmpty() ) {
//					System.out.println("Notify."+r);
					notifyAll();
				}
			}
		}
	}

	public Object take() {
		if (results.isEmpty()) {
			synchronized (this) {
				waiting = true;
				try {
					wait();
				} catch (InterruptedException ie) {
					waiting = false;
				}
				if (results.isEmpty()) {
					// Reawaken by shutdown
//					System.out.println("Shutdown.");
					return null;
				}
			}
		}
		return results.remove(0);
	}
}
