ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.65
Committed: Tue May 19 06:32:59 2015 UTC (9 years ago) by jsr166
Branch: MAIN
Changes since 1.64: +2 -8 lines
Log Message:
replace eq with (standard) Objects.equals

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/publicdomain/zero/1.0/
5 */
6
7 package java.util.concurrent;
8
9 import java.util.AbstractSet;
10 import java.util.Collection;
11 import java.util.Iterator;
12 import java.util.Objects;
13 import java.util.Set;
14 import java.util.Spliterator;
15 import java.util.Spliterators;
16 import java.util.function.Consumer;
17 import java.util.function.Predicate;
18
19 /**
20 * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList}
21 * for all of its operations. Thus, it shares the same basic properties:
22 * <ul>
23 * <li>It is best suited for applications in which set sizes generally
24 * stay small, read-only operations
25 * vastly outnumber mutative operations, and you need
26 * to prevent interference among threads during traversal.
27 * <li>It is thread-safe.
28 * <li>Mutative operations ({@code add}, {@code set}, {@code remove}, etc.)
29 * are expensive since they usually entail copying the entire underlying
30 * array.
31 * <li>Iterators do not support the mutative {@code remove} operation.
32 * <li>Traversal via iterators is fast and cannot encounter
33 * interference from other threads. Iterators rely on
34 * unchanging snapshots of the array at the time the iterators were
35 * constructed.
36 * </ul>
37 *
38 * <p><b>Sample Usage.</b> The following code sketch uses a
39 * copy-on-write set to maintain a set of Handler objects that
40 * perform some action upon state updates.
41 *
42 * <pre> {@code
43 * class Handler { void handle(); ... }
44 *
45 * class X {
46 * private final CopyOnWriteArraySet<Handler> handlers
47 * = new CopyOnWriteArraySet<>();
48 * public void addHandler(Handler h) { handlers.add(h); }
49 *
50 * private long internalState;
51 * private synchronized void changeState() { internalState = ...; }
52 *
53 * public void update() {
54 * changeState();
55 * for (Handler handler : handlers)
56 * handler.handle();
57 * }
58 * }}</pre>
59 *
60 * <p>This class is a member of the
61 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
62 * Java Collections Framework</a>.
63 *
64 * @see CopyOnWriteArrayList
65 * @since 1.5
66 * @author Doug Lea
67 * @param <E> the type of elements held in this set
68 */
69 public class CopyOnWriteArraySet<E> extends AbstractSet<E>
70 implements java.io.Serializable {
71 private static final long serialVersionUID = 5457747651344034263L;
72
73 private final CopyOnWriteArrayList<E> al;
74
75 /**
76 * Creates an empty set.
77 */
78 public CopyOnWriteArraySet() {
79 al = new CopyOnWriteArrayList<E>();
80 }
81
82 /**
83 * Creates a set containing all of the elements of the specified
84 * collection.
85 *
86 * @param c the collection of elements to initially contain
87 * @throws NullPointerException if the specified collection is null
88 */
89 public CopyOnWriteArraySet(Collection<? extends E> c) {
90 if (c.getClass() == CopyOnWriteArraySet.class) {
91 @SuppressWarnings("unchecked") CopyOnWriteArraySet<E> cc =
92 (CopyOnWriteArraySet<E>)c;
93 al = new CopyOnWriteArrayList<E>(cc.al);
94 }
95 else {
96 al = new CopyOnWriteArrayList<E>();
97 al.addAllAbsent(c);
98 }
99 }
100
101 /**
102 * Returns the number of elements in this set.
103 *
104 * @return the number of elements in this set
105 */
106 public int size() {
107 return al.size();
108 }
109
110 /**
111 * Returns {@code true} if this set contains no elements.
112 *
113 * @return {@code true} if this set contains no elements
114 */
115 public boolean isEmpty() {
116 return al.isEmpty();
117 }
118
119 /**
120 * Returns {@code true} if this set contains the specified element.
121 * More formally, returns {@code true} if and only if this set
122 * contains an element {@code e} such that {@code Objects.equals(o, e)}.
123 *
124 * @param o element whose presence in this set is to be tested
125 * @return {@code true} if this set contains the specified element
126 */
127 public boolean contains(Object o) {
128 return al.contains(o);
129 }
130
131 /**
132 * Returns an array containing all of the elements in this set.
133 * If this set makes any guarantees as to what order its elements
134 * are returned by its iterator, this method must return the
135 * elements in the same order.
136 *
137 * <p>The returned array will be "safe" in that no references to it
138 * are maintained by this set. (In other words, this method must
139 * allocate a new array even if this set is backed by an array).
140 * The caller is thus free to modify the returned array.
141 *
142 * <p>This method acts as bridge between array-based and collection-based
143 * APIs.
144 *
145 * @return an array containing all the elements in this set
146 */
147 public Object[] toArray() {
148 return al.toArray();
149 }
150
151 /**
152 * Returns an array containing all of the elements in this set; the
153 * runtime type of the returned array is that of the specified array.
154 * If the set fits in the specified array, it is returned therein.
155 * Otherwise, a new array is allocated with the runtime type of the
156 * specified array and the size of this set.
157 *
158 * <p>If this set fits in the specified array with room to spare
159 * (i.e., the array has more elements than this set), the element in
160 * the array immediately following the end of the set is set to
161 * {@code null}. (This is useful in determining the length of this
162 * set <i>only</i> if the caller knows that this set does not contain
163 * any null elements.)
164 *
165 * <p>If this set makes any guarantees as to what order its elements
166 * are returned by its iterator, this method must return the elements
167 * in the same order.
168 *
169 * <p>Like the {@link #toArray()} method, this method acts as bridge between
170 * array-based and collection-based APIs. Further, this method allows
171 * precise control over the runtime type of the output array, and may,
172 * under certain circumstances, be used to save allocation costs.
173 *
174 * <p>Suppose {@code x} is a set known to contain only strings.
175 * The following code can be used to dump the set into a newly allocated
176 * array of {@code String}:
177 *
178 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
179 *
180 * Note that {@code toArray(new Object[0])} is identical in function to
181 * {@code toArray()}.
182 *
183 * @param a the array into which the elements of this set are to be
184 * stored, if it is big enough; otherwise, a new array of the same
185 * runtime type is allocated for this purpose.
186 * @return an array containing all the elements in this set
187 * @throws ArrayStoreException if the runtime type of the specified array
188 * is not a supertype of the runtime type of every element in this
189 * set
190 * @throws NullPointerException if the specified array is null
191 */
192 public <T> T[] toArray(T[] a) {
193 return al.toArray(a);
194 }
195
196 /**
197 * Removes all of the elements from this set.
198 * The set will be empty after this call returns.
199 */
200 public void clear() {
201 al.clear();
202 }
203
204 /**
205 * Removes the specified element from this set if it is present.
206 * More formally, removes an element {@code e} such that
207 * {@code Objects.equals(o, e)}, if this set contains such an element.
208 * Returns {@code true} if this set contained the element (or
209 * equivalently, if this set changed as a result of the call).
210 * (This set will not contain the element once the call returns.)
211 *
212 * @param o object to be removed from this set, if present
213 * @return {@code true} if this set contained the specified element
214 */
215 public boolean remove(Object o) {
216 return al.remove(o);
217 }
218
219 /**
220 * Adds the specified element to this set if it is not already present.
221 * More formally, adds the specified element {@code e} to this set if
222 * the set contains no element {@code e2} such that
223 * {@code Objects.equals(e, e2)}.
224 * If this set already contains the element, the call leaves the set
225 * unchanged and returns {@code false}.
226 *
227 * @param e element to be added to this set
228 * @return {@code true} if this set did not already contain the specified
229 * element
230 */
231 public boolean add(E e) {
232 return al.addIfAbsent(e);
233 }
234
235 /**
236 * Returns {@code true} if this set contains all of the elements of the
237 * specified collection. If the specified collection is also a set, this
238 * method returns {@code true} if it is a <i>subset</i> of this set.
239 *
240 * @param c collection to be checked for containment in this set
241 * @return {@code true} if this set contains all of the elements of the
242 * specified collection
243 * @throws NullPointerException if the specified collection is null
244 * @see #contains(Object)
245 */
246 public boolean containsAll(Collection<?> c) {
247 return al.containsAll(c);
248 }
249
250 /**
251 * Adds all of the elements in the specified collection to this set if
252 * they're not already present. If the specified collection is also a
253 * set, the {@code addAll} operation effectively modifies this set so
254 * that its value is the <i>union</i> of the two sets. The behavior of
255 * this operation is undefined if the specified collection is modified
256 * while the operation is in progress.
257 *
258 * @param c collection containing elements to be added to this set
259 * @return {@code true} if this set changed as a result of the call
260 * @throws NullPointerException if the specified collection is null
261 * @see #add(Object)
262 */
263 public boolean addAll(Collection<? extends E> c) {
264 return al.addAllAbsent(c) > 0;
265 }
266
267 /**
268 * Removes from this set all of its elements that are contained in the
269 * specified collection. If the specified collection is also a set,
270 * this operation effectively modifies this set so that its value is the
271 * <i>asymmetric set difference</i> of the two sets.
272 *
273 * @param c collection containing elements to be removed from this set
274 * @return {@code true} if this set changed as a result of the call
275 * @throws ClassCastException if the class of an element of this set
276 * is incompatible with the specified collection (optional)
277 * @throws NullPointerException if this set contains a null element and the
278 * specified collection does not permit null elements (optional),
279 * or if the specified collection is null
280 * @see #remove(Object)
281 */
282 public boolean removeAll(Collection<?> c) {
283 return al.removeAll(c);
284 }
285
286 /**
287 * Retains only the elements in this set that are contained in the
288 * specified collection. In other words, removes from this set all of
289 * its elements that are not contained in the specified collection. If
290 * the specified collection is also a set, this operation effectively
291 * modifies this set so that its value is the <i>intersection</i> of the
292 * two sets.
293 *
294 * @param c collection containing elements to be retained in this set
295 * @return {@code true} if this set changed as a result of the call
296 * @throws ClassCastException if the class of an element of this set
297 * is incompatible with the specified collection (optional)
298 * @throws NullPointerException if this set contains a null element and the
299 * specified collection does not permit null elements (optional),
300 * or if the specified collection is null
301 * @see #remove(Object)
302 */
303 public boolean retainAll(Collection<?> c) {
304 return al.retainAll(c);
305 }
306
307 /**
308 * Returns an iterator over the elements contained in this set
309 * in the order in which these elements were added.
310 *
311 * <p>The returned iterator provides a snapshot of the state of the set
312 * when the iterator was constructed. No synchronization is needed while
313 * traversing the iterator. The iterator does <em>NOT</em> support the
314 * {@code remove} method.
315 *
316 * @return an iterator over the elements in this set
317 */
318 public Iterator<E> iterator() {
319 return al.iterator();
320 }
321
322 /**
323 * Compares the specified object with this set for equality.
324 * Returns {@code true} if the specified object is the same object
325 * as this object, or if it is also a {@link Set} and the elements
326 * returned by an {@linkplain Set#iterator() iterator} over the
327 * specified set are the same as the elements returned by an
328 * iterator over this set. More formally, the two iterators are
329 * considered to return the same elements if they return the same
330 * number of elements and for every element {@code e1} returned by
331 * the iterator over the specified set, there is an element
332 * {@code e2} returned by the iterator over this set such that
333 * {@code Objects.equals(e1, e2)}.
334 *
335 * @param o object to be compared for equality with this set
336 * @return {@code true} if the specified object is equal to this set
337 */
338 public boolean equals(Object o) {
339 if (o == this)
340 return true;
341 if (!(o instanceof Set))
342 return false;
343 Set<?> set = (Set<?>)o;
344 Iterator<?> it = set.iterator();
345
346 // Uses O(n^2) algorithm that is only appropriate
347 // for small sets, which CopyOnWriteArraySets should be.
348
349 // Use a single snapshot of underlying array
350 Object[] elements = al.getArray();
351 int len = elements.length;
352 // Mark matched elements to avoid re-checking
353 boolean[] matched = new boolean[len];
354 int k = 0;
355 outer: while (it.hasNext()) {
356 if (++k > len)
357 return false;
358 Object x = it.next();
359 for (int i = 0; i < len; ++i) {
360 if (!matched[i] && Objects.equals(x, elements[i])) {
361 matched[i] = true;
362 continue outer;
363 }
364 }
365 return false;
366 }
367 return k == len;
368 }
369
370 public boolean removeIf(Predicate<? super E> filter) {
371 return al.removeIf(filter);
372 }
373
374 public void forEach(Consumer<? super E> action) {
375 al.forEach(action);
376 }
377
378 /**
379 * Returns a {@link Spliterator} over the elements in this set in the order
380 * in which these elements were added.
381 *
382 * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
383 * {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and
384 * {@link Spliterator#SUBSIZED}.
385 *
386 * <p>The spliterator provides a snapshot of the state of the set
387 * when the spliterator was constructed. No synchronization is needed while
388 * operating on the spliterator. The spliterator does <em>NOT</em> support
389 * the {@code remove}, {@code set} or {@code add} methods.
390 *
391 * @return a {@code Spliterator} over the elements in this set
392 * @since 1.8
393 */
394 public Spliterator<E> spliterator() {
395 return Spliterators.spliterator
396 (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT);
397 }
398 }