java.util.concurrent.BlockingQueue.peek()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.2k)|赞(0)|评价(0)|浏览(158)

本文整理了Java中java.util.concurrent.BlockingQueue.peek()方法的一些代码示例,展示了BlockingQueue.peek()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。BlockingQueue.peek()方法的具体详情如下:
包路径:java.util.concurrent.BlockingQueue
类名称:BlockingQueue
方法名:peek

BlockingQueue.peek介绍

暂无

代码示例

代码示例来源:origin: apache/hbase

@Override
public Runnable peek() {
 return underlyingQueue.peek();
}

代码示例来源:origin: square/okhttp

@Override public MockResponse peek() {
 MockResponse peek = responseQueue.peek();
 if (peek != null) return peek;
 if (failFastResponse != null) return failFastResponse;
 return super.peek();
}

代码示例来源:origin: apache/pulsar

public long getDelayInMillis() {
  OpSendMsg firstMsg = pendingMessages.peek();
  if (firstMsg != null) {
    return System.currentTimeMillis() - firstMsg.createdAt;
  }
  return 0L;
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

@Override
public E peek() {
 return takeRef.get().peek();
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

/**
 * Peek, like poll, provides no strict consistency.
 */
@Override
public E peek() {
 E e = null;
 for (int i=0; e == null && i < queues.size(); i++) {
  e = queues.get(i).peek();
 }
 return e;
}

代码示例来源:origin: square/okhttp

@Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
 // To permit interactive/browser testing, ignore requests for favicons.
 final String requestLine = request.getRequestLine();
 if (requestLine != null && requestLine.equals("GET /favicon.ico HTTP/1.1")) {
  logger.info("served " + requestLine);
  return new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
 }
 if (failFastResponse != null && responseQueue.peek() == null) {
  // Fail fast if there's no response queued up.
  return failFastResponse;
 }
 MockResponse result = responseQueue.take();
 // If take() returned because we're shutting down, then enqueue another dead letter so that any
 // other threads waiting on take() will also return.
 if (result == DEAD_LETTER) responseQueue.add(DEAD_LETTER);
 return result;
}

代码示例来源:origin: robovm/robovm

/**
 * Constrains the values of all delays in the queue to be within
 * Long.MAX_VALUE of each other, to avoid overflow in compareTo.
 * This may occur if a task is eligible to be dequeued, but has
 * not yet been, while some other task is added with a delay of
 * Long.MAX_VALUE.
 */
private long overflowFree(long delay) {
  Delayed head = (Delayed) super.getQueue().peek();
  if (head != null) {
    long headDelay = head.getDelay(NANOSECONDS);
    if (headDelay < 0 && (delay - headDelay < 0))
      delay = Long.MAX_VALUE + headDelay;
  }
  return delay;
}

代码示例来源:origin: apache/pulsar

private void removeExpiredMessagesFromQueue(Set<MessageId> messageIds) {
  Message<T> peek = incomingMessages.peek();
  if (peek != null) {
    if (!messageIds.contains(peek.getMessageId())) {
      // first message is not expired, then no message is expired in queue.
      return;
    }
    // try not to remove elements that are added while we remove
    Message<T> message = incomingMessages.poll();
    checkState(message instanceof TopicMessageImpl);
    while (message != null) {
      MessageId messageId = message.getMessageId();
      if (!messageIds.contains(messageId)) {
        messageIds.add(messageId);
        break;
      }
      message = incomingMessages.poll();
    }
  }
}

代码示例来源:origin: alibaba/canal

/**
 * 通知下一个minTimestamp数据出队列
 * 
 * @throws InterruptedException
 */
private void single(long timestamp) throws InterruptedException {
  lastTimestamps.add(timestamp);
  if (timestamp < state()) {
    // 针对mysql事务中会出现时间跳跃
    // 例子:
    // 2012-08-08 16:24:26 事务头
    // 2012-08-08 16:24:24 变更记录
    // 2012-08-08 16:24:25 变更记录
    // 2012-08-08 16:24:26 事务尾
    // 针对这种case,一旦发现timestamp有回退的情况,直接更新threshold,强制阻塞其他的操作,等待最小数据优先处理完成
    threshold = timestamp; // 更新为最小值
  }
  if (lastTimestamps.size() >= groupSize) {// 判断队列是否需要触发
    // 触发下一个出队列的数据
    Long minTimestamp = this.lastTimestamps.peek();
    if (minTimestamp != null) {
      threshold = minTimestamp;
      notify(minTimestamp);
    }
  } else {
    threshold = Long.MIN_VALUE;// 如果不满足队列长度,需要阻塞等待
  }
}

代码示例来源:origin: apache/hbase

public Path getCurrentPath() {
 // if we've read some WAL entries, get the Path we read from
 WALEntryBatch batchQueueHead = entryBatchQueue.peek();
 if (batchQueueHead != null) {
  return batchQueueHead.getLastWalPath();
 }
 // otherwise, we must be currently reading from the head of the log queue
 return logQueue.peek();
}

代码示例来源:origin: apache/nifi

private boolean deleteBasedOnTimestamp(final BlockingQueue<ArchiveInfo> fileQueue, final long removalTimeThreshold) throws IOException {
  // check next file's last mod time.
  final ArchiveInfo nextFile = fileQueue.peek();
  if (nextFile == null) {
    // Continue on to queue up the files, in case the next file must be destroyed based on time.
    return false;
  }
  // If the last mod time indicates that it should be removed, just continue loop.
  final long oldestArchiveDate = getLastModTime(nextFile.toPath());
  return (oldestArchiveDate <= removalTimeThreshold);
}

代码示例来源:origin: google/guava

/** Perform a {@code put} and assert that operation completed in the expected timeframe. */
void putSuccessfully() {
 putUninterruptibly(queue, "");
 completed.assertCompletionExpected();
 assertEquals("", queue.peek());
}

代码示例来源:origin: apache/rocketmq

public long headSlowTimeMills(BlockingQueue<Runnable> q) {
  long slowTimeMills = 0;
  final Runnable peek = q.peek();
  if (peek != null) {
    RequestTask rt = BrokerFastFailure.castRunnable(peek);
    slowTimeMills = rt == null ? 0 : this.messageStore.now() - rt.getCreateTimestamp();
  }
  if (slowTimeMills < 0) {
    slowTimeMills = 0;
  }
  return slowTimeMills;
}

代码示例来源:origin: google/guava

public void testPutWithNoWait() {
 Stopwatch stopwatch = Stopwatch.createStarted();
 BlockingQueue<String> queue = new ArrayBlockingQueue<>(999);
 putUninterruptibly(queue, "");
 assertTimeNotPassed(stopwatch, LONG_DELAY_MS);
 assertEquals("", queue.peek());
}

代码示例来源:origin: apache/rocketmq

void cleanExpiredRequestInQueue(final BlockingQueue<Runnable> blockingQueue, final long maxWaitTimeMillsInQueue) {
  while (true) {
    try {
      if (!blockingQueue.isEmpty()) {
        final Runnable runnable = blockingQueue.peek();
        if (null == runnable) {
          break;
        }
        final RequestTask rt = castRunnable(runnable);
        if (rt == null || rt.isStopRun()) {
          break;
        }
        final long behind = System.currentTimeMillis() - rt.getCreateTimestamp();
        if (behind >= maxWaitTimeMillsInQueue) {
          if (blockingQueue.remove(runnable)) {
            rt.setStopRun(true);
            rt.returnResponse(RemotingSysResponseCode.SYSTEM_BUSY, String.format("[TIMEOUT_CLEAN_QUEUE]broker busy, start flow control for a while, period in queue: %sms, size of queue: %d", behind, blockingQueue.size()));
          }
        } else {
          break;
        }
      } else {
        break;
      }
    } catch (Throwable ignored) {
    }
  }
}

代码示例来源:origin: apache/ignite

/**
 * Check and throws an exception if happens during this factory threads execution.
 *
 * @throws Exception If there is error.
 */
public void checkError() throws Exception {
  Throwable err = errors.peek();
  if (err != null) {
    if (err instanceof Error)
      throw (Error)err;
    throw (Exception)err;
  }
  for (GridTestThread thread : threads) {
    thread.checkError();
  }
}

代码示例来源:origin: apache/incubator-gobblin

private void drainQueue(BlockingQueue<Pair<AbstractDocument, Future>> queue, int threshold, long sleepTime,
  TimeUnit sleepUnit, List<Pair<AbstractDocument, Future>> failedFutures) {
 while (queue.remainingCapacity() < threshold) {
  if (sleepTime > 0) {
   Pair<AbstractDocument, Future> topElement = queue.peek();
   if (topElement != null) {
    try {
     topElement.getSecond().get(sleepTime, sleepUnit);
    } catch (Exception te) {
     failedFutures.add(topElement);
    }
    queue.poll();
   }
  }
 }
}

代码示例来源:origin: google/guava

/** Checks that #drain() invocations behave correctly for a drained (empty) queue. */
private void assertDrained(BlockingQueue<Object> q) {
 assertNull(q.peek());
 assertInterruptibleDrained(q);
 assertUninterruptibleDrained(q);
}

代码示例来源:origin: google/guava

void checkEmpty(BlockingQueue q) {
 try {
  assertTrue(q.isEmpty());
  assertEquals(0, q.size());
  assertNull(q.peek());
  assertNull(q.poll());
  assertNull(q.poll(0, MILLISECONDS));
  assertEquals("[]", q.toString());
  assertTrue(Arrays.equals(q.toArray(), new Object[0]));
  assertFalse(q.iterator().hasNext());
  try {
   q.element();
   shouldThrow();
  } catch (NoSuchElementException success) {
  }
  try {
   q.iterator().next();
   shouldThrow();
  } catch (NoSuchElementException success) {
  }
  try {
   q.remove();
   shouldThrow();
  } catch (NoSuchElementException success) {
  }
 } catch (InterruptedException ie) {
  threadUnexpectedException(ie);
 }
}

代码示例来源:origin: ben-manes/caffeine

void checkEmpty(BlockingQueue q) {
  try {
    assertTrue(q.isEmpty());
    assertEquals(0, q.size());
    assertNull(q.peek());
    assertNull(q.poll());
    assertNull(q.poll(0, MILLISECONDS));
    assertEquals(q.toString(), "[]");
    assertTrue(Arrays.equals(q.toArray(), new Object[0]));
    assertFalse(q.iterator().hasNext());
    try {
      q.element();
      shouldThrow();
    } catch (NoSuchElementException success) {}
    try {
      q.iterator().next();
      shouldThrow();
    } catch (NoSuchElementException success) {}
    try {
      q.remove();
      shouldThrow();
    } catch (NoSuchElementException success) {}
  } catch (InterruptedException fail) { threadUnexpectedException(fail); }
}

相关文章