/* File: MessageQueue.java
 * Contains: A class for thread communication
 * Author: Jeff Dalton <J.Dalton@ed.ac.uk>
 * Created: January 1998
 * Updated: Wed Sep 27 12:14:20 2000 by Jeff Dalton
 * Copyright: (c) 1998, AIAI, University of Edinburgh
 */

package ix.util;

import java.util.*;


/**
 * MessageQueues can be used for messages between threads.
 */

// For now, it's easiest just to use a vector to hold the elements.

public class MessageQueue {

    Vector contents = new Vector();

    public MessageQueue() {
	super();
    }

    public synchronized void send(Object message) {
	contents.addElement(message);
	// Optimization: notify only if (contents.size() == 1) // if was empty
	notifyAll();
    }

    public synchronized Object nextMessage() {
	while (contents.isEmpty()) {
	    try { wait(); }
	    catch (InterruptedException e) {}
	}
	Object message = contents.elementAt(0);
	contents.removeElementAt(0);
	return message;
    }

    public synchronized boolean waitForMessage() {
	// Returns true if there's a message, false if not.
	if (contents.isEmpty()) {
	    try { wait(); }
	    catch (InterruptedException e) {}
	}
	return !contents.isEmpty();
    }

    public synchronized boolean waitForMessage(long timeout) {
	// Returns true if there's a message, false if not.
	if (contents.isEmpty()) {
	    try { wait(timeout); }
	    catch (InterruptedException e) {}
	}
	return !contents.isEmpty();
    }

    public synchronized boolean hasMessage() {
	return !contents.isEmpty();
    }

    public synchronized void clear() {
	contents.removeAllElements();
    }

}

