// $Id: Queue.java.concurrent,v 1.1.1.1 2003/09/09 01:24:12 belaban Exp $

package org.jgroups.util;


import org.jgroups.TimeoutException;
import org.jgroups.log.Trace;

import java.util.Vector;

import EDU.oswego.cs.dl.util.concurrent.WaitFreeQueue;




/**
 * Elements are added at the tail and removed from the head. Class is thread-safe in that
 * 1 producer and 1 consumer may add/remove elements concurrently. The class is not
 * explicitely designed for multiple producers or consumers. Implemented as a linked
 * list, so that removal of an element at the head does not cause a right-shift of the
 * remaining elements (as in a Vector-based implementation).
 * @author Bela Ban
 * @author Filip Hanik
 */
public class Queue extends WaitFreeQueue {
    boolean closed=false;
    int     size=0;


    public Queue() {
    }

    public Object getFirst() {
        return super.peek();
    }

    public Object getLast() {
        return null; // not implemented
    }

    public boolean closed() {
        return closed;
    }

    public void add(Object obj) throws QueueClosedException {
        try {
            super.put(obj);
            size++;
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void addAtHead(Object obj) throws QueueClosedException {
        try {
            super.put(obj);
            size++;
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Object remove() throws QueueClosedException {
        Object retval=null;
        try {
            retval=super.take();
            size--;
            return retval;
        }
        catch(InterruptedException e) {
            e.printStackTrace();
            return retval;
        }
    }

    public Object remove(long timeout) throws QueueClosedException, TimeoutException {
        return remove();
    }

    public void removeElement(Object obj) throws QueueClosedException {
        ;
    }

    public Object peek() {
        return super.peek();
    }

    public Object peek(long timeout) throws QueueClosedException, TimeoutException {
        return peek();
    }

    public void close(boolean flush_entries) {
        closed=true;
    }

    public void reset() {
        closed=false;
        size=0;
    }

    public int size() {
        return size;
    }

    public String toString() {
        return super.toString();
    }



}
