1 26 27 package net.sourceforge.groboutils.util.datastruct.v1; 28 29 30 84 public class SynchQueue 85 { 86 89 private static class ListElement 90 { 91 public Object value; 92 public volatile ListElement next; 93 public ListElement() {} 94 public ListElement( Object o ) 95 { 96 this.value = o; 97 } 98 } 99 100 104 private ListElement head, tail; 105 106 109 private volatile int size = 0; 110 111 112 113 116 public SynchQueue() 117 { 118 this.head = new ListElement(); 119 this.tail = new ListElement(); 120 this.tail.next = new ListElement(); 121 } 122 123 124 132 public void enqueue( Object o ) 133 { 134 ListElement le = new ListElement( o ); 135 synchronized( le ) 136 { 137 138 153 synchronized( this.head ) 154 { 155 if (this.head.next == null) 156 { 157 this.head.next = le; 158 this.head.notify(); 159 } 160 } 161 162 synchronized( this.tail.next ) 163 { 164 this.size++; 165 this.tail.next.next = le; 166 this.tail.next = le; 167 } 168 } 169 } 170 171 172 186 public Object dequeue() 187 throws InterruptedException 188 { 189 return dequeue( 0, 0 ); 190 } 191 192 193 218 public Object dequeue( long timeout ) 219 throws InterruptedException 220 { 221 return dequeue( timeout, 0 ); 222 } 223 224 225 252 public Object dequeue( long timeout, int nanos ) 253 throws InterruptedException 254 { 255 Object o; 256 float dTimeout = (float)(timeout + nanos); 257 258 259 synchronized( this.head ) 260 { 261 if (this.head.next == null) 264 { 265 if (timeout < 0) 267 { 268 return null; 269 } 270 while (true) 271 { 272 this.head.wait( timeout, nanos ); 273 274 if (this.head.next != null) 276 { 277 break; 279 } 280 281 if (dTimeout > 0.9f) 285 { 286 return null; 289 } 290 } 291 } 293 o = this.head.next.value; 295 296 this.head.next.value = null; 298 299 synchronized( this.head.next ) 300 { 301 this.head.next = this.head.next.next; 302 this.size--; 303 } 304 } 305 return o; 306 } 307 308 309 319 public Object peek() 320 { 321 Object o = null; 322 323 synchronized( this.head ) 324 { 325 if (this.head.next != null) 326 { 327 o = this.head.next.value; 328 } 329 } 331 return o; 332 } 333 334 335 343 public boolean isEmpty() 344 { 345 return (this.head.next == null); 346 } 347 348 349 354 public int size() 355 { 356 return this.size; 357 } 358 359 360 363 public void removeAll() 364 { 365 synchronized( this.head ) 366 { 367 synchronized( this.tail.next ) 368 { 369 this.head.next = null; 370 371 this.tail.next.value = null; 373 374 this.size = 0; 375 } 376 } 377 } 378 379 } 380 381 | Popular Tags |