1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
4 /** A simple synchronized queue, implemented as an array */
7 public Queue(int initiallength) { vec = new Object[initiallength]; }
12 /** The index of the first node in the queue */
13 private int first = 0;
15 /** The number of elements in the queue; INVARAINT: size <= vec.length */
18 /** Grow the queue, if needed */
19 private void grow(int newlength) {
20 Object[] newvec = new Object[newlength];
21 if (first + size > vec.length) {
22 System.arraycopy(vec, first, newvec, 0, vec.length - first);
23 System.arraycopy(vec, 0, newvec, vec.length - first, size - (vec.length - first));
25 System.arraycopy(vec, first, newvec, 0, size);
31 /** The number of elements in the queue */
32 public int size() { return size; }
34 /** Empties the queue */
35 public synchronized void flush() {
38 for(int i=0; i<vec.length; i++) vec[i] = null;
41 /** Add an element to the queue */
42 public synchronized void append(Object o) {
43 if (size == vec.length) grow(vec.length * 2);
44 if (first + size >= vec.length) vec[first + size - vec.length] = o;
45 else vec[first + size] = o;
47 if (size == 1) notify();
50 /** Remove and return and element from the queue, blocking if empty. */
51 public Object remove() { return remove(true); }
53 /** Remove and return an element from the queue, blocking if
54 <tt>block</tt> is true and the queue is empty. */
55 public synchronized Object remove(boolean block) {
58 if (!block) return null;
61 } catch (InterruptedException e) {
62 } catch (Exception e) {
63 if (Log.on) Log.log(this, "exception in Queue.wait(); this should never happen");
64 if (Log.on) Log.log(this, e);
68 Object ret = vec[first];
71 if (first >= vec.length) first = 0;
75 /** Returns the top element in the queue without removing it */
76 public synchronized Object peek() {
77 if (size == 0) return null;