1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.collect;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21
22 import com.google.common.annotations.Beta;
23 import com.google.common.annotations.GwtIncompatible;
24 import com.google.common.annotations.VisibleForTesting;
25
26 import java.io.Serializable;
27 import java.util.ArrayDeque;
28 import java.util.Collection;
29 import java.util.Queue;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 @Beta
45 @GwtIncompatible("java.util.ArrayDeque")
46 public final class EvictingQueue<E> extends ForwardingQueue<E> implements Serializable {
47
48 private final Queue<E> delegate;
49
50 @VisibleForTesting
51 final int maxSize;
52
53 private EvictingQueue(int maxSize) {
54 checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize);
55 this.delegate = new ArrayDeque<E>(maxSize);
56 this.maxSize = maxSize;
57 }
58
59
60
61
62
63
64
65 public static <E> EvictingQueue<E> create(int maxSize) {
66 return new EvictingQueue<E>(maxSize);
67 }
68
69
70
71
72
73
74
75 public int remainingCapacity() {
76 return maxSize - size();
77 }
78
79 @Override protected Queue<E> delegate() {
80 return delegate;
81 }
82
83
84
85
86
87
88
89 @Override public boolean offer(E e) {
90 return add(e);
91 }
92
93
94
95
96
97
98
99 @Override public boolean add(E e) {
100 checkNotNull(e);
101 if (maxSize == 0) {
102 return true;
103 }
104 if (size() == maxSize) {
105 delegate.remove();
106 }
107 delegate.add(e);
108 return true;
109 }
110
111 @Override public boolean addAll(Collection<? extends E> collection) {
112 return standardAddAll(collection);
113 }
114
115 @Override
116 public boolean contains(Object object) {
117 return delegate().contains(checkNotNull(object));
118 }
119
120 @Override
121 public boolean remove(Object object) {
122 return delegate().remove(checkNotNull(object));
123 }
124
125
126
127 private static final long serialVersionUID = 0L;
128 }