1 45 package org.exolab.jms.common.util; 46 47 48 67 public class FifoQueue { 68 69 72 private Object [] _queue; 73 74 77 private final int _capacity; 78 79 82 private int _size; 83 84 87 private int _head; 88 89 92 private int _tail; 93 94 101 public FifoQueue(int capacity) { 102 _capacity = (capacity > 0) ? capacity : 1; _queue = new Object [_capacity]; 104 _head = 0; 105 _tail = 0; 106 _size = 0; 107 } 108 109 114 public int getCapacity() { 115 return _capacity; 116 } 117 118 123 public synchronized int getSize() { 124 return _size; 125 } 126 127 132 public synchronized boolean isEmpty() { 133 return (_size == 0); 134 } 135 136 141 public synchronized boolean isFull() { 142 return (_size == _capacity); 143 } 144 145 154 public synchronized void add(Object obj) throws InterruptedException { 155 waitWhileFull(); 156 157 _queue[_head] = obj; 158 _head = (_head + 1) % _capacity; 159 _size++; 160 notifyAll(); 161 } 162 163 172 public synchronized void add(Object [] list) throws InterruptedException { 173 for (int i = 0; i < list.length; i++) { 177 add(list[i]); 178 } 179 } 180 181 190 public synchronized Object get() throws InterruptedException { 191 waitWhileEmpty(); 192 193 Object obj = _queue[_tail]; 194 195 _queue[_tail] = null; 197 198 _tail = (_tail + 1) % _capacity; 199 _size--; 200 notifyAll(); 201 return obj; 202 } 203 204 215 public synchronized Object [] getAll() throws InterruptedException { 216 Object [] list = new Object [_size]; 217 218 for (int i = 0; i < list.length; i++) { 219 list[i] = get(); 220 } 221 return list; 222 } 223 224 238 public synchronized boolean waitUntilEmpty(long timeout) 239 throws InterruptedException { 240 if (timeout == 0L) { 241 waitUntilEmpty(); 242 return true; 243 } 244 245 long endTime = System.currentTimeMillis() + timeout; 247 long remaining = timeout; 248 249 while (!isEmpty() && (remaining > 0L)) { 250 wait(remaining); 251 remaining = endTime - System.currentTimeMillis(); 252 } 253 return isEmpty(); 254 } 255 256 261 public synchronized void waitUntilEmpty() throws InterruptedException { 262 while (!isEmpty()) { 263 wait(); 264 } 265 } 266 267 272 public synchronized void waitWhileEmpty() throws InterruptedException { 273 while (isEmpty()) { 274 wait(); 275 } 276 } 277 278 283 public synchronized void waitUntilFull() throws InterruptedException { 284 while (!isFull()) { 285 wait(); 286 } 287 } 288 289 294 public synchronized void waitWhileFull() throws InterruptedException { 295 while (isFull()) { 296 wait(); 297 } 298 } 299 } 300 | Popular Tags |