001: /*
002: * Copyright 1999-2004 The Apache Software Foundation
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.apache.tomcat.util.collections;
018:
019: import java.util.Vector;
020:
021: /**
022: * A simple FIFO queue class which causes the calling thread to wait
023: * if the queue is empty and notifies threads that are waiting when it
024: * is not empty.
025: *
026: * @author Anil V (akv@eng.sun.com)
027: */
028: public class Queue {
029: private Vector vector = new Vector();
030: private boolean stopWaiting = false;
031: private boolean waiting = false;
032:
033: /**
034: * Put the object into the queue.
035: *
036: * @param object the object to be appended to the
037: * queue.
038: */
039: public synchronized void put(Object object) {
040: vector.addElement(object);
041: notify();
042: }
043:
044: /** Break the pull(), allowing the calling thread to exit
045: */
046: public synchronized void stop() {
047: stopWaiting = true;
048: // just a hack to stop waiting
049: if (waiting)
050: notify();
051: }
052:
053: /**
054: * Pull the first object out of the queue. Wait if the queue is
055: * empty.
056: */
057: public synchronized Object pull() {
058: while (isEmpty()) {
059: try {
060: waiting = true;
061: wait();
062: } catch (InterruptedException ex) {
063: }
064: waiting = false;
065: if (stopWaiting)
066: return null;
067: }
068: return get();
069: }
070:
071: /**
072: * Get the first object out of the queue. Return null if the queue
073: * is empty.
074: */
075: public synchronized Object get() {
076: Object object = peek();
077: if (object != null)
078: vector.removeElementAt(0);
079: return object;
080: }
081:
082: /**
083: * Peek to see if something is available.
084: */
085: public Object peek() {
086: if (isEmpty())
087: return null;
088: return vector.elementAt(0);
089: }
090:
091: /**
092: * Is the queue empty?
093: */
094: public boolean isEmpty() {
095: return vector.isEmpty();
096: }
097:
098: /**
099: * How many elements are there in this queue?
100: */
101: public int size() {
102: return vector.size();
103: }
104: }
|