1 16 package org.mortbay.util; 17 18 19 27 public class BlockingQueue 28 { 29 31 Object [] elements; 32 Object lock; 33 int maxSize; 34 int size=0; 35 int head=0; 36 int tail=0; 37 38 39 41 public BlockingQueue(int maxSize) 42 { 43 this(null,maxSize); 44 } 45 46 47 49 public BlockingQueue(Object lock, int maxSize) 50 { 51 this.maxSize=maxSize; 52 if (maxSize==0) 53 this.maxSize=255; 54 elements = new Object [this.maxSize]; 55 this.lock=lock==null?elements:lock; 56 } 57 58 59 public void clear() 60 { 61 synchronized(lock) 62 { 63 size=0; 64 head=0; 65 tail=0; 66 } 67 } 68 69 70 public int size() 71 { 72 return size; 73 } 74 75 76 public int maxSize() 77 { 78 return maxSize; 79 } 80 81 82 83 86 public void put(Object o) 87 throws InterruptedException 88 { 89 synchronized(lock) 90 { 91 while (size==maxSize) 92 lock.wait(); 93 94 elements[tail]=o; 95 if(++tail==maxSize) 96 tail=0; 97 size++; 98 lock.notify(); 99 } 100 } 101 102 103 108 public void put(Object o, int timeout) 109 throws InterruptedException 110 { 111 synchronized(lock) 112 { 113 if (size==maxSize) 114 { 115 lock.wait(timeout); 116 if (size==maxSize) 117 throw new InterruptedException ("Timed out"); 118 } 119 120 elements[tail]=o; 121 if(++tail==maxSize) 122 tail=0; 123 size++; 124 lock.notify(); 125 } 126 } 127 128 129 133 public Object get() 134 throws InterruptedException 135 { 136 synchronized(lock) 137 { 138 while (size==0) 139 lock.wait(); 140 141 Object o = elements[head]; 142 elements[head]=null; 143 if(++head==maxSize) 144 head=0; 145 if (size==maxSize) 146 lock.notifyAll(); 147 size--; 148 return o; 149 } 150 } 151 152 153 154 159 public Object get(int timeoutMs) 160 throws InterruptedException 161 { 162 synchronized(lock) 163 { 164 if (size==0 && timeoutMs!=0) 165 lock.wait((long)timeoutMs); 166 167 if (size==0) 168 return null; 169 170 Object o = elements[head]; 171 elements[head]=null; 172 if(++head==maxSize) 173 head=0; 174 175 if (size==maxSize) 176 lock.notifyAll(); 177 size--; 178 179 return o; 180 } 181 } 182 183 184 188 public Object peek() 189 throws InterruptedException 190 { 191 synchronized(lock) 192 { 193 if (size==0) 194 lock.wait(); 195 196 if (size==0) 197 return null; 198 199 Object o = elements[head]; 200 return o; 201 } 202 } 203 204 205 210 public Object peek(int timeoutMs) 211 throws InterruptedException 212 { 213 synchronized(lock) 214 { 215 if (size==0) 216 lock.wait((long)timeoutMs); 217 218 if (size==0) 219 return null; 220 221 Object o = elements[head]; 222 return o; 223 } 224 } 225 } 226 227 228 229 230 231 232 233 234 | Popular Tags |