public RunnableScheduledFuture<?> poll(long timeout, TimeUnit unit)
     throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         if (nanos <= 0) return null;
         if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos);
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             long timeLeft = available.awaitNanos(delay);
             nanos -= delay - timeLeft;
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
示例#2
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();
   }
 }
示例#3
0
  public Session take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      while (active) {
        Session first = queue.peek();
        if (first == null) {
          available.await();
        } else {
          long delay = getDelay(first, TimeUnit.NANOSECONDS);
          if (delay > 0) {
            available.awaitNanos(delay);
          } else {
            Session x = queue.poll();
            assert x != null;
            if (queue.size() != 0) {
              available.signalAll(); // wake up other takers
            }
            return x;
          }
        }
      }

      throw new InterruptedException("Session queue is stopping");
    } finally {
      lock.unlock();
    }
  }
示例#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) return q.poll();
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && q.peek() != null) available.signal();
     lock.unlock();
   }
 }
  public Events<Event> get(Position start, int batchSize, long timeout, TimeUnit unit)
      throws InterruptedException, CanalStoreException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (checkUnGetSlotAt((LogPosition) start, batchSize)) {
          return doGet(start, batchSize);
        }

        if (nanos <= 0) {
          // 如果时间到了,有多少取多少
          return doGet(start, batchSize);
        }

        try {
          nanos = notEmpty.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notEmpty.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
  public boolean put(List<Event> data, long timeout, TimeUnit unit)
      throws InterruptedException, CanalStoreException {
    if (data == null || data.isEmpty()) {
      return true;
    }

    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (checkFreeSlotAt(putSequence.get() + data.size())) {
          doPut(data);
          return true;
        }
        if (nanos <= 0) {
          return false;
        }

        try {
          nanos = notFull.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notFull.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
 public RunnableScheduledFuture<?> take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) available.await();
       else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
示例#8
0
  /**
   * Blocks until an object is received that is handled by process, or the specified timeout has
   * passed.
   *
   * <p>Once closed any attempt to wait will throw an exception.
   *
   * @param timeout The timeout in milliseconds.
   * @return The object that resolved the blocking.
   * @throws QpidException
   * @throws FailoverException
   */
  public Object block(long timeout) throws QpidException, FailoverException {
    if (timeout < 0) {
      throw new IllegalArgumentException("timeout must be zero or greater");
    }

    long nanoTimeout = TimeUnit.MILLISECONDS.toNanos(timeout);

    _lock.lock();

    try {
      if (_closed) {
        throw throwClosedException();
      }

      if (_error == null) {
        _waiting.set(true);

        while (!_ready && _error == null) {
          try {
            nanoTimeout = _receivedCondition.awaitNanos(nanoTimeout);

            if (nanoTimeout <= 0 && !_ready && _error == null) {
              _error = new AMQTimeoutException("Server did not respond in a timely fashion", null);
              _ready = true;
            }
          } catch (InterruptedException e) {
            _logger.error(e.getMessage(), e);
            // IGNORE    -- //fixme this isn't ideal as being interrupted isn't equivalent to
            // success
          }
        }
      }

      if (_error != null) {
        if (_error instanceof QpidException) {
          throw (QpidException) _error;
        } else if (_error instanceof FailoverException) {
          // This should ensure that FailoverException is not wrapped and can be caught.
          throw (FailoverException) _error; // needed to expose FailoverException.
        } else {
          throw new QpidException("Woken up due to " + _error.getClass(), _error);
        }
      }

    } finally {
      _waiting.set(false);

      // Release Error handling thread
      if (_error != null) {
        _errorAck = true;
        _errorConditionAck.signal();

        _error = null;
      }
      _lock.unlock();
    }

    return _doneObject;
  }
 @Override
 public E pollFirst(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   E result;
   try {
     while ((result = removeAt(0)) == null && nanos > 0) nanos = notEmpty.awaitNanos(nanos);
   } finally {
     lock.unlock();
   }
   return result;
 }
 @Override
 public E pollLast(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lock();
   E result;
   try {
     int indexMax = indexOfLargerChild(deque, size, 0, comparator);
     int indexRemove = indexMax > 0 ? indexMax : 0;
     while ((result = removeAt(indexRemove)) == null && nanos > 0)
       nanos = notEmpty.awaitNanos(nanos);
   } finally {
     lock.unlock();
   }
   return result;
 }
示例#11
0
 @Override
 public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   lock.lock();
   try {
     for (; ; ) {
       if (isTerminated()) {
         return true;
       } else if (nanos <= 0) {
         return false;
       } else {
         nanos = termination.awaitNanos(nanos);
       }
     }
   } finally {
     lock.unlock();
   }
 }
 @Override
 public List<OTEServerLocation> findServerByMachine(String regex, long timeoutMs)
     throws URISyntaxException {
   lock.lock();
   List<OTEServerLocation> locations = findServerByMachine(regex);
   try {
     long nanos = TimeUnit.MILLISECONDS.toNanos(timeoutMs);
     while (nanos > 0 && locations.size() == 0) {
       try {
         nanos = condition.awaitNanos(nanos);
         locations = findServerByMachine(regex);
       } catch (InterruptedException e) {
         e.printStackTrace();
       }
     }
   } finally {
     lock.unlock();
   }
   return locations;
 }
 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       if (count != 0) {
         E x = extract();
         return x;
       }
       if (nanos <= 0) return null;
       try {
         nanos = notEmpty.awaitNanos(nanos);
       } catch (InterruptedException ie) {
         notEmpty.signal(); // propagate to non-interrupted thread
         throw ie;
       }
     }
   } finally {
     lock.unlock();
   }
 }
  /**
   * Inserts the specified element at the tail of this queue, waiting up to the specified wait time
   * for space to become available if the queue is full.
   *
   * @throws InterruptedException {@inheritDoc}
   * @throws NullPointerException {@inheritDoc}
   */
  public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {

    if (e == null) throw new NullPointerException();
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
      for (; ; ) {
        if (count != items.length) {
          insert(e);
          return true;
        }
        if (nanos <= 0) return false;
        try {
          nanos = notFull.awaitNanos(nanos);
        } catch (InterruptedException ie) {
          notFull.signal(); // propagate to non-interrupted thread
          throw ie;
        }
      }
    } finally {
      lock.unlock();
    }
  }
  public void waitUntilOffset(long offset, long timeout, TimeUnit timeUnit) throws StoreException {
    if (offset < 0) {
      throw new StoreException("KafkaStoreReaderThread can't wait for a negative offset.");
    }

    log.trace("Waiting to read offset {}. Currently at offset {}", offset, offsetInSchemasTopic);

    try {
      offsetUpdateLock.lock();
      long timeoutNs = TimeUnit.NANOSECONDS.convert(timeout, timeUnit);
      while ((offsetInSchemasTopic < offset) && (timeoutNs > 0)) {
        try {
          timeoutNs = offsetReachedThreshold.awaitNanos(timeoutNs);
        } catch (InterruptedException e) {
          log.debug(
              "Interrupted while waiting for the background store reader thread to reach"
                  + " the specified offset: "
                  + offset,
              e);
        }
      }
    } finally {
      offsetUpdateLock.unlock();
    }

    if (offsetInSchemasTopic < offset) {
      throw new StoreTimeoutException(
          "KafkaStoreReaderThread failed to reach target offset within the timeout interval. "
              + "targetOffset: "
              + offset
              + ", offsetReached: "
              + offsetInSchemasTopic
              + ", timeout(ms): "
              + TimeUnit.MILLISECONDS.convert(timeout, timeUnit));
    }
  }
示例#16
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();
   }
 }
示例#17
0
  public Object down(Event evt) {
    switch (evt.getType()) {
      case Event.LOCK:
        LockInfo info = (LockInfo) evt.getArg();
        ClientLock lock = getLock(info.getName());
        if (!info.isTrylock()) {
          if (info.isLockInterruptibly()) {
            try {
              lock.lockInterruptibly();
            } catch (InterruptedException e) {
              Thread.currentThread()
                  .interrupt(); // has to be checked by caller who has to rethrow ...
            }
          } else lock.lock();
        } else {
          if (info.isUseTimeout()) {
            try {
              return lock.tryLock(info.getTimeout(), info.getTimeUnit());
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
            }
          } else {
            return lock.tryLock();
          }
        }
        return null;

      case Event.UNLOCK:
        info = (LockInfo) evt.getArg();
        lock = getLock(info.getName(), false);
        if (lock != null) lock.unlock();
        return null;

      case Event.UNLOCK_ALL:
        unlockAll();
        return null;
      case Event.LOCK_AWAIT:
        info = (LockInfo) evt.getArg();
        lock = getLock(info.getName(), false);
        if (lock == null || !lock.acquired) {
          throw new IllegalMonitorStateException();
        }
        Condition condition = lock.newCondition();
        if (info.isUseTimeout()) {
          try {
            return condition.awaitNanos(info.getTimeUnit().toNanos(info.getTimeout()));
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        } else if (info.isLockInterruptibly()) {
          try {
            condition.await();
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        } else {
          condition.awaitUninterruptibly();
        }
        break;
      case Event.LOCK_SIGNAL:
        AwaitInfo awaitInfo = (AwaitInfo) evt.getArg();
        lock = getLock(awaitInfo.getName(), false);
        if (lock == null || !lock.acquired) {
          throw new IllegalMonitorStateException();
        }
        sendSignalConditionRequest(awaitInfo.getName(), awaitInfo.isAll());
        break;
      case Event.SET_LOCAL_ADDRESS:
        local_addr = (Address) evt.getArg();
        break;

      case Event.VIEW_CHANGE:
        handleView((View) evt.getArg());
        break;
    }
    return down_prot.down(evt);
  }