1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
10 /** A simple synchronized queue, implemented as an array */
13 public Queue(int initiallength) { vec = new Object[initiallength]; }
18 /** The index of the first node in the queue */
19 private int first = 0;
21 /** The number of elements in the queue; INVARAINT: size <= vec.length */
24 /** Grow the queue, if needed */
25 private void grow(int newlength) {
26 Object[] newvec = new Object[newlength];
27 if (first + size > vec.length) {
28 System.arraycopy(vec, first, newvec, 0, vec.length - first);
29 System.arraycopy(vec, 0, newvec, vec.length - first, size - (vec.length - first));
31 System.arraycopy(vec, first, newvec, 0, size);
37 /** The number of elements in the queue */
38 public int size() { return size; }
40 /** Empties the queue */
41 public synchronized void flush() {
44 for(int i=0; i<vec.length; i++) vec[i] = null;
47 /** Add an element to the front of the queue */
48 public synchronized void prepend(Object o) {
49 if (size == vec.length) grow(vec.length * 2);
51 if (first < 0) first += vec.length;
54 if (size == 1) notify();
57 /** Add an element to the back of the queue */
58 public synchronized void append(Object o) {
59 if (size == vec.length) grow(vec.length * 2);
60 if (first + size >= vec.length) vec[first + size - vec.length] = o;
61 else vec[first + size] = o;
63 if (size == 1) notify();
66 /** Remove and return and element from the queue, blocking if empty. */
67 public Object remove() { return remove(true); }
69 /** Remove and return an element from the queue, blocking if
70 <tt>block</tt> is true and the queue is empty. */
71 public synchronized Object remove(boolean block) {
73 while (size == 0 && block) {
74 try { wait(); } catch (InterruptedException e) { }
77 if (!block && size == 0) return null;
78 Object ret = vec[first];
81 if (first >= vec.length) first = 0;
85 /** Returns the top element in the queue without removing it */
86 public synchronized Object peek() {
87 if (size == 0) return null;