java.util.ArrayDeque类的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(8.4k)|赞(0)|评价(0)|浏览(156)

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

ArrayDeque介绍

[英]Resizable-array implementation of the Deque interface. Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedListwhen used as a queue.

Most ArrayDeque operations run in amortized constant time. Exceptions include #remove(Object), #removeFirstOccurrence, #removeLastOccurrence, #contains, #iterator, and the bulk operations, all of which run in linear time.

The iterators returned by this class's iterator method are fail-fast: If the deque is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will generally throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.
[中]Deque接口的可调整大小的数组实现。阵列设备没有容量限制;它们根据需要增长以支持使用。它们不是线程安全的;在没有外部同步的情况下,它们不支持多线程并发访问。禁止使用空元素。当用作堆栈时,此类可能比堆栈快,当用作队列时,此类可能比LinkedList快。
大多数ArrayDeque操作在摊销的固定时间内运行。例外情况包括#remove(Object)、#removeFirstOccurrence、#removelastorcurrence、#contains、#迭代器和批量操作,所有这些操作都以线性时间运行。
这个类的迭代器方法返回的迭代器是快速失效的:如果在迭代器创建之后的任何时候,以迭代器自己的remove方法以外的任何方式修改了deque,迭代器通常会抛出ConcurrentModificationException。因此,在面对并发修改时,迭代器会快速、干净地失败,而不是在将来的不确定时间冒着任意、不确定行为的风险。
请注意,无法保证迭代器的快速失效行为,因为一般来说,在存在非同步并发修改的情况下,不可能做出任何硬保证。快速失败迭代器会尽最大努力抛出ConcurrentModificationException。因此,编写依赖于此异常的正确性的程序是错误的:迭代器的快速失败行为应该只用于检测bug。
此类及其迭代器实现集合和迭代器接口的所有可选方法。

代码示例

代码示例来源:origin: ReactiveX/RxJava

BufferSkipObserver(Observer<? super U> actual, int count, int skip, Callable<U> bufferSupplier) {
  this.downstream = actual;
  this.count = count;
  this.skip = skip;
  this.bufferSupplier = bufferSupplier;
  this.buffers = new ArrayDeque<U>();
}

代码示例来源:origin: ReactiveX/RxJava

/**
 * Returns a flattened list of Throwables from tree-like CompositeException chain.
 * @param t the starting throwable
 * @return the list of Throwables flattened in a depth-first manner
 */
public static List<Throwable> flatten(Throwable t) {
  List<Throwable> list = new ArrayList<Throwable>();
  ArrayDeque<Throwable> deque = new ArrayDeque<Throwable>();
  deque.offer(t);
  while (!deque.isEmpty()) {
    Throwable e = deque.removeFirst();
    if (e instanceof CompositeException) {
      CompositeException ce = (CompositeException) e;
      List<Throwable> exceptions = ce.getExceptions();
      for (int i = exceptions.size() - 1; i >= 0; i--) {
        deque.offerFirst(exceptions.get(i));
      }
    } else {
      list.add(e);
    }
  }
  return list;
}

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

public DefaultBlockingPool(
  Supplier<T> generator,
  int limit
)
{
 this.objects = new ArrayDeque<>(limit);
 this.maxSize = limit;
 for (int i = 0; i < limit; i++) {
  objects.add(generator.get());
 }
 this.lock = new ReentrantLock();
 this.notEnough = lock.newCondition();
}

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

synchronized boolean pong(ByteString payload) {
 // Don't send pongs after we've failed or sent the close frame.
 if (failed || (enqueuedClose && messageAndCloseQueue.isEmpty())) return false;
 pongQueue.add(payload);
 runWriter();
 return true;
}

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

@Nullable
private T pollObject()
{
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
  return objects.isEmpty() ? null : objects.pop();
 }
 finally {
  lock.unlock();
 }
}

代码示例来源:origin: ReactiveX/RxJava

@Override
public void onError(Throwable t) {
  final ArrayDeque<UnicastSubject<T>> ws = windows;
  while (!ws.isEmpty()) {
    ws.poll().onError(t);
  }
  downstream.onError(t);
}

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

@Override
public AsyncResult poll() throws InterruptedException {
  lock.lockInterruptibly();
  try {
    while (queue.isEmpty() || !queue.peek().isDone()) {
      headIsCompleted.await();
    }
    notFull.signalAll();
    LOG.debug("Polled head element from ordered stream element queue. New filling degree " +
      "({}/{}).", queue.size() - 1, capacity);
    return queue.poll();
  } finally {
    lock.unlock();
  }
}

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

private void processAtomEnded(long atomEndPosition) throws ParserException {
 while (!containerAtoms.isEmpty() && containerAtoms.peek().endPosition == atomEndPosition) {
  Atom.ContainerAtom containerAtom = containerAtoms.pop();
  if (containerAtom.type == Atom.TYPE_moov) {
   // We've reached the end of the moov atom. Process it and prepare to read samples.
   processMoovAtom(containerAtom);
   containerAtoms.clear();
   parserState = STATE_READING_SAMPLE;
  } else if (!containerAtoms.isEmpty()) {
   containerAtoms.peek().add(containerAtom);
  }
 }
 if (parserState != STATE_READING_SAMPLE) {
  enterReadingAtomHeaderState();
 }
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * @return true if this iterator has a "next" element
 */
@Override
public boolean hasNext() {
 return !pathStack.isEmpty();
}

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

@Override
public AsyncResult peekBlockingly() throws InterruptedException {
  lock.lockInterruptibly();
  try {
    while (queue.isEmpty() || !queue.peek().isDone()) {
      headIsCompleted.await();
    }
    LOG.debug("Peeked head element from ordered stream element queue with filling degree " +
      "({}/{}).", queue.size(), capacity);
    return queue.peek();
  } finally {
    lock.unlock();
  }
}

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

private void processAtomEnded(long atomEndPosition) throws ParserException {
 while (!containerAtoms.isEmpty() && containerAtoms.peek().endPosition == atomEndPosition) {
  onContainerAtomRead(containerAtoms.pop());
 }
 enterReadingAtomHeaderState();
}

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

@Override
public void add(BufferOrEvent boe) {
  bytesBlocked += pageSize;
  currentBuffers.add(boe);
}

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

/**
 * Get the number of elements in this queue added via one of the {@link #add(ByteBuf)} methods.
 * @return the number of elements in this queue.
 */
protected final int size() {
  return bufAndListenerPairs.size();
}

代码示例来源:origin: ReactiveX/RxJava

@Override
public void onNext(T t) {
  final ArrayDeque<UnicastSubject<T>> ws = windows;
  long i = index;
  long s = skip;
  if (i % s == 0 && !cancelled) {
    wip.getAndIncrement();
    UnicastSubject<T> w = UnicastSubject.create(capacityHint, this);
    ws.offer(w);
    downstream.onNext(w);
  }
  long c = firstEmission + 1;
  for (UnicastSubject<T> w : ws) {
    w.onNext(t);
  }
  if (c >= count) {
    ws.poll().onComplete();
    if (ws.isEmpty() && cancelled) {
      this.upstream.dispose();
      return;
    }
    firstEmission = c - s;
  } else {
    firstEmission = c;
  }
  index = i + 1;
}

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

private void onContainerAtomRead(ContainerAtom container) throws ParserException {
 if (container.type == Atom.TYPE_moov) {
  onMoovContainerAtomRead(container);
 } else if (container.type == Atom.TYPE_moof) {
  onMoofContainerAtomRead(container);
 } else if (!containerAtoms.isEmpty()) {
  containerAtoms.peek().add(container);
 }
}

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

@Override
public final O dequeueOutputBuffer() throws E {
 synchronized (lock) {
  maybeThrowException();
  if (queuedOutputBuffers.isEmpty()) {
   return null;
  }
  return queuedOutputBuffers.removeFirst();
 }
}

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

@Override
public SubtitleInputBuffer dequeueInputBuffer() throws SubtitleDecoderException {
 Assertions.checkState(dequeuedInputBuffer == null);
 if (availableInputBuffers.isEmpty()) {
  return null;
 }
 dequeuedInputBuffer = availableInputBuffers.pollFirst();
 return dequeuedInputBuffer;
}

代码示例来源:origin: eclipse-vertx/vert.x

@Override
void handleClose() {
 if (pendingPushes.remove(this)) {
  completionHandler.fail("Push reset by client");
 } else {
  concurrentStreams--;
  while ((maxConcurrentStreams == null || concurrentStreams < maxConcurrentStreams) && pendingPushes.size() > 0) {
   Push push = pendingPushes.pop();
   concurrentStreams++;
   context.runOnContext(v -> {
    push.complete();
   });
  }
  response.handleClose();
 }
}

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

private List<T> takeObjects(int elementNum) throws InterruptedException
{
 final List<T> list = new ArrayList<>(elementNum);
 final ReentrantLock lock = this.lock;
 lock.lockInterruptibly();
 try {
  while (objects.size() < elementNum) {
   notEnough.await();
  }
  for (int i = 0; i < elementNum; i++) {
   list.add(objects.pop());
  }
  return list;
 }
 finally {
  lock.unlock();
 }
}

代码示例来源:origin: bumptech/glide

@Override
public Bitmap get(int width, int height, Bitmap.Config config) {
 return bitmaps.isEmpty() ? null : bitmaps.removeLast();
}

相关文章

微信公众号

最新文章

更多