427 |
|
/** |
428 |
|
* Returns an iterator over all the elements (both expired and |
429 |
|
* unexpired) in this queue. The iterator does not |
430 |
< |
* return the elements in any particular order. The returned |
431 |
< |
* iterator is a thread-safe "fast-fail" iterator that will throw |
432 |
< |
* {@link ConcurrentModificationException} upon detected |
433 |
< |
* interference. |
430 |
> |
* return the elements in any particular order. |
431 |
|
* |
432 |
|
* @return an iterator over the elements in this queue |
433 |
|
*/ |
434 |
|
public Iterator<E> iterator() { |
435 |
< |
final ReentrantLock lock = this.lock; |
439 |
< |
lock.lock(); |
440 |
< |
try { |
441 |
< |
return new Itr<E>(q.iterator()); |
442 |
< |
} finally { |
443 |
< |
lock.unlock(); |
444 |
< |
} |
435 |
> |
return new Itr<E>(toArray()); |
436 |
|
} |
437 |
|
|
438 |
+ |
/** |
439 |
+ |
* Snapshot iterator that works off copy of underlying q array. |
440 |
+ |
*/ |
441 |
|
private class Itr<E> implements Iterator<E> { |
442 |
< |
private final Iterator<E> iter; |
443 |
< |
Itr(Iterator<E> i) { |
444 |
< |
iter = i; |
442 |
> |
final Object[] array; // Array of all elements |
443 |
> |
int cursor; // index of next element to return; |
444 |
> |
int lastRet; // index of last element, or -1 if no such |
445 |
> |
|
446 |
> |
Itr(Object[] array) { |
447 |
> |
lastRet = -1; |
448 |
> |
this.array = array; |
449 |
|
} |
450 |
|
|
451 |
|
public boolean hasNext() { |
452 |
< |
return iter.hasNext(); |
452 |
> |
return cursor < array.length; |
453 |
|
} |
454 |
|
|
455 |
|
public E next() { |
456 |
< |
final ReentrantLock lock = DelayQueue.this.lock; |
457 |
< |
lock.lock(); |
458 |
< |
try { |
459 |
< |
return iter.next(); |
462 |
< |
} finally { |
463 |
< |
lock.unlock(); |
464 |
< |
} |
456 |
> |
if (cursor >= array.length) |
457 |
> |
throw new NoSuchElementException(); |
458 |
> |
lastRet = cursor; |
459 |
> |
return (E)array[cursor++]; |
460 |
|
} |
461 |
|
|
462 |
|
public void remove() { |
463 |
< |
final ReentrantLock lock = DelayQueue.this.lock; |
463 |
> |
if (lastRet < 0) |
464 |
> |
throw new IllegalStateException(); |
465 |
> |
Object x = array[lastRet]; |
466 |
> |
lastRet = -1; |
467 |
> |
// Traverse underlying queue to find == element, |
468 |
> |
// not just a .equals element. |
469 |
|
lock.lock(); |
470 |
|
try { |
471 |
< |
iter.remove(); |
471 |
> |
for (Iterator it = q.iterator(); it.hasNext(); ) { |
472 |
> |
if (it.next() == x) { |
473 |
> |
it.remove(); |
474 |
> |
return; |
475 |
> |
} |
476 |
> |
} |
477 |
|
} finally { |
478 |
|
lock.unlock(); |
479 |
|
} |