1
2
3
4
5
6
7
8 package org.xwt.util;
9
10
11 public class Queue {
12
13 public Queue(int initiallength) { vec = new Object[initiallength]; }
14
15
16 private Object[] vec;
17
18
19 private int first = 0;
20
21
22 private int size = 0;
23
24
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));
30 } else {
31 System.arraycopy(vec, first, newvec, 0, size);
32 }
33 first = 0;
34 vec = newvec;
35 }
36
37
38 public int size() { return size; }
39
40
41 public synchronized void flush() {
42 first = 0;
43 size = 0;
44 for(int i=0; i<vec.length; i++) vec[i] = null;
45 }
46
47
48 public synchronized void prepend(Object o) {
49 if (size == vec.length) grow(vec.length * 2);
50 first--;
51 if (first < 0) first += vec.length;
52 vec[first] = o;
53 size++;
54 if (size == 1) notify();
55 }
56
57
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;
62 size++;
63 if (size == 1) notify();
64 }
65
66
67 public Object remove() { return remove(true); }
68
69
71 public synchronized Object remove(boolean block) {
72
73 while (size == 0) {
74 if (!block) return null;
75 try {
76 wait();
77 } catch (InterruptedException e) {
78 } catch (Exception e) {
79 if (Log.on) Log.info(this, "exception in Queue.wait(); this should never happen");
80 if (Log.on) Log.info(this, e);
81 }
82 }
83
84 Object ret = vec[first];
85 first++;
86 size--;
87 if (first >= vec.length) first = 0;
88 return ret;
89 }
90
91
92 public synchronized Object peek() {
93 if (size == 0) return null;
94 return vec[first];
95 }
96
97 }
98