Esempio n. 1
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue, or the specified wait time expires.
  *
  * @return the head of this queue, or <tt>null</tt> if the specified waiting time elapses before
  *     an element with an expired delay becomes available
  * @throws InterruptedException {@inheritDoc}
  */
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay > 0) {
           if (nanos <= 0) return null;
           if (delay > nanos) delay = nanos;
           long timeLeft = available.awaitNanos(delay);
           nanos -= delay - timeLeft;
         } else {
           E x = q.poll();
           assert x != null;
           if (q.size() != 0) available.signalAll();
           return x;
         }
       }
     }
   } finally {
     lock.unlock();
   }
 }
Esempio n. 2
0
 public int size() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     return q.size();
   } finally {
     lock.unlock();
   }
 }
Esempio n. 3
0
 /**
  * Retrieves and removes the head of this queue, or returns <tt>null</tt> if this queue has no
  * elements with an expired delay.
  *
  * @return the head of this queue, or <tt>null</tt> if this queue has no elements with an expired
  *     delay
  */
 public E poll() {
   final ReentrantLock lock = this.lock;
   lock.lock();
   try {
     E first = q.peek();
     if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0) return null;
     else {
       E x = q.poll();
       assert x != null;
       if (q.size() != 0) available.signalAll();
       return x;
     }
   } finally {
     lock.unlock();
   }
 }
Esempio n. 4
0
 /**
  * Retrieves and removes the head of this queue, waiting if necessary until an element with an
  * expired delay is available on this queue.
  *
  * @return the head of this queue
  * @throws InterruptedException {@inheritDoc}
  */
 public E take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       E first = q.peek();
       if (first == null) {
         available.await();
       } else {
         long delay = first.getDelay(TimeUnit.NANOSECONDS);
         if (delay > 0) {
           long tl = available.awaitNanos(delay);
         } else {
           E x = q.poll();
           assert x != null;
           if (q.size() != 0) available.signalAll(); // wake up other takers
           return x;
         }
       }
     }
   } finally {
     lock.unlock();
   }
 }