001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.VisibleForTesting;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import java.io.Serializable;
027import java.util.ArrayDeque;
028import java.util.Collection;
029import java.util.Queue;
030
031/**
032 * A non-blocking queue which automatically evicts elements from the head of the queue when
033 * attempting to add new elements onto the queue and it is full. This queue orders elements FIFO
034 * (first-in-first-out). This data structure is logically equivalent to a circular buffer (i.e.,
035 * cyclic buffer or ring buffer).
036 *
037 * <p>An evicting queue must be configured with a maximum size. Each time an element is added to a
038 * full queue, the queue automatically removes its head element. This is different from conventional
039 * bounded queues, which either block or reject new elements when full.
040 *
041 * <p>This class is not thread-safe, and does not accept null elements.
042 *
043 * @author Kurt Alfred Kluever
044 * @since 15.0
045 */
046@Beta
047@GwtCompatible
048@ElementTypesAreNonnullByDefault
049public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serializable {
050
051  private final Queue<E> delegate;
052
053  @VisibleForTesting final int maxSize;
054
055  private EvictingQueue(int maxSize) {
056    checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize);
057    this.delegate = new ArrayDeque<>(maxSize);
058    this.maxSize = maxSize;
059  }
060
061  /**
062   * Creates and returns a new evicting queue that will hold up to {@code maxSize} elements.
063   *
064   * <p>When {@code maxSize} is zero, elements will be evicted immediately after being added to the
065   * queue.
066   */
067  public static <E> EvictingQueue<E> create(int maxSize) {
068    return new EvictingQueue<>(maxSize);
069  }
070
071  /**
072   * Returns the number of additional elements that this queue can accept without evicting; zero if
073   * the queue is currently full.
074   *
075   * @since 16.0
076   */
077  public int remainingCapacity() {
078    return maxSize - size();
079  }
080
081  @Override
082  protected Queue<E> delegate() {
083    return delegate;
084  }
085
086  /**
087   * Adds the given element to this queue. If the queue is currently full, the element at the head
088   * of the queue is evicted to make room.
089   *
090   * @return {@code true} always
091   */
092  @Override
093  @CanIgnoreReturnValue
094  public boolean offer(E e) {
095    return add(e);
096  }
097
098  /**
099   * Adds the given element to this queue. If the queue is currently full, the element at the head
100   * of the queue is evicted to make room.
101   *
102   * @return {@code true} always
103   */
104  @Override
105  @CanIgnoreReturnValue
106  public boolean add(E e) {
107    checkNotNull(e); // check before removing
108    if (maxSize == 0) {
109      return true;
110    }
111    if (size() == maxSize) {
112      delegate.remove();
113    }
114    delegate.add(e);
115    return true;
116  }
117
118  @Override
119  @CanIgnoreReturnValue
120  public boolean addAll(Collection<? extends E> collection) {
121    int size = collection.size();
122    if (size >= maxSize) {
123      clear();
124      return Iterables.addAll(this, Iterables.skip(collection, size - maxSize));
125    }
126    return standardAddAll(collection);
127  }
128
129  @Override
130  public Object[] toArray() {
131    /*
132     * If we could, we'd declare the no-arg `Collection.toArray()` to return "Object[] but elements
133     * have the same nullness as E." Since we can't, we declare it to return nullable elements, and
134     * we can override it in our non-null-guaranteeing subtypes to present a better signature to
135     * their users.
136     *
137     * However, the checker *we* use has this special knowledge about `Collection.toArray()` anyway,
138     * so in our implementation code, we can rely on that. That's why the expression below
139     * type-checks.
140     */
141    return super.toArray();
142  }
143
144  private static final long serialVersionUID = 0L;
145}