001: /* Copyright 2001 The JA-SIG Collaborative. All rights reserved.
002: * See license distributed with this file and
003: * available online at http://www.uportal.org/license.html
004: */
005:
006: package org.jasig.portal.utils;
007:
008: import java.util.LinkedList;
009:
010: /**
011: * A simple FIFO queue that has MIN/MAX capacity and
012: * that blocks if either enqueue/dequeue would result
013: * in violation of these limits.
014: * Default values for min/max are 0/infinite
015: * @author Peter Kharchenko
016: */
017:
018: public class BlockingQueue {
019: int maxSize;
020: int minSize;
021:
022: volatile LinkedList queue = null;
023:
024: BlockingQueue() {
025: maxSize = -1;
026: minSize = 0;
027: queue = new LinkedList();
028: }
029:
030: /**
031: * Construct a new blocking queue with predefined max/min limits
032: */
033: BlockingQueue(int min, int max) {
034: this ();
035: maxSize = max;
036: minSize = min;
037: }
038:
039: BlockingQueue(int max) {
040: this (0, max);
041: }
042:
043: /**
044: * Add new object to the end of the queue
045: * @param o object to be placed on the queue
046: */
047: public synchronized void enqueue(Object o)
048: throws InterruptedException {
049: // while((queue.size()>=maxSize) || maxSize!=-1) {
050: while (queue.size() >= maxSize && maxSize != -1) {
051: wait();
052: }
053: queue.addLast(o);
054: notifyAll();
055: }
056:
057: /**
058: * Remove object from the beginning of the queue
059: * @throws InterruptedException if the wait was interrupted
060: */
061: public synchronized Object dequeue() throws InterruptedException {
062: while (queue.size() <= minSize) {
063: wait();
064: }
065: notifyAll();
066: return queue.removeFirst();
067: }
068:
069: /**
070: * Set the queue limits.
071: * To specify a queue without an upper bound (that is max=inifinity) use max value of -1
072: */
073: public synchronized void setLimits(int max, int min) {
074: maxSize = max;
075: minSize = min;
076: notifyAll();
077: }
078:
079: public int getMaxSize() {
080: return maxSize;
081: }
082:
083: public int getMinSize() {
084: return minSize;
085: }
086:
087: public synchronized void setMaxSize(int max) {
088: maxSize = max;
089: notifyAll();
090: }
091:
092: public synchronized void setMinSize(int min) {
093: minSize = min;
094: notifyAll();
095: }
096:
097: public synchronized int size() {
098: return queue.size();
099: }
100: }
|