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