ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.56
Committed: Thu Aug 8 15:13:34 2013 UTC (10 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.55: +16 -0 lines
Log Message:
add javadoc for spliterator()

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 import java.util.Collection;
9 import java.util.Collections;
10 import java.util.Set;
11 import java.util.AbstractSet;
12 import java.util.Iterator;
13 import java.util.Spliterator;
14 import java.util.Spliterators;
15 import java.util.function.Predicate;
16 import java.util.function.Consumer;
17
18 /**
19 * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList}
20 * for all of its operations. Thus, it shares the same basic properties:
21 * <ul>
22 * <li>It is best suited for applications in which set sizes generally
23 * stay small, read-only operations
24 * vastly outnumber mutative operations, and you need
25 * to prevent interference among threads during traversal.
26 * <li>It is thread-safe.
27 * <li>Mutative operations ({@code add}, {@code set}, {@code remove}, etc.)
28 * are expensive since they usually entail copying the entire underlying
29 * array.
30 * <li>Iterators do not support the mutative {@code remove} operation.
31 * <li>Traversal via iterators is fast and cannot encounter
32 * interference from other threads. Iterators rely on
33 * unchanging snapshots of the array at the time the iterators were
34 * constructed.
35 * </ul>
36 *
37 * <p><b>Sample Usage.</b> The following code sketch uses a
38 * copy-on-write set to maintain a set of Handler objects that
39 * perform some action upon state updates.
40 *
41 * <pre> {@code
42 * class Handler { void handle(); ... }
43 *
44 * class X {
45 * private final CopyOnWriteArraySet<Handler> handlers
46 * = new CopyOnWriteArraySet<Handler>();
47 * public void addHandler(Handler h) { handlers.add(h); }
48 *
49 * private long internalState;
50 * private synchronized void changeState() { internalState = ...; }
51 *
52 * public void update() {
53 * changeState();
54 * for (Handler handler : handlers)
55 * handler.handle();
56 * }
57 * }}</pre>
58 *
59 * <p>This class is a member of the
60 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
61 * Java Collections Framework</a>.
62 *
63 * @see CopyOnWriteArrayList
64 * @since 1.5
65 * @author Doug Lea
66 * @param <E> the type of elements held in this collection
67 */
68 public class CopyOnWriteArraySet<E> extends AbstractSet<E>
69 implements java.io.Serializable {
70 private static final long serialVersionUID = 5457747651344034263L;
71
72 private final CopyOnWriteArrayList<E> al;
73
74 /**
75 * Creates an empty set.
76 */
77 public CopyOnWriteArraySet() {
78 al = new CopyOnWriteArrayList<E>();
79 }
80
81 /**
82 * Creates a set containing all of the elements of the specified
83 * collection.
84 *
85 * @param c the collection of elements to initially contain
86 * @throws NullPointerException if the specified collection is null
87 */
88 public CopyOnWriteArraySet(Collection<? extends E> c) {
89 if (c.getClass() == CopyOnWriteArraySet.class) {
90 @SuppressWarnings("unchecked") CopyOnWriteArraySet<E> cc =
91 (CopyOnWriteArraySet<E>)c;
92 al = new CopyOnWriteArrayList<E>(cc.al);
93 }
94 else {
95 al = new CopyOnWriteArrayList<E>();
96 al.addAllAbsent(c);
97 }
98 }
99
100 /**
101 * Returns the number of elements in this set.
102 *
103 * @return the number of elements in this set
104 */
105 public int size() {
106 return al.size();
107 }
108
109 /**
110 * Returns {@code true} if this set contains no elements.
111 *
112 * @return {@code true} if this set contains no elements
113 */
114 public boolean isEmpty() {
115 return al.isEmpty();
116 }
117
118 /**
119 * Returns {@code true} if this set contains the specified element.
120 * More formally, returns {@code true} if and only if this set
121 * contains an element {@code e} such that
122 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
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 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>,
208 * if this set contains such an element. Returns {@code true} if
209 * this set contained the element (or equivalently, if this set
210 * changed as a result of the call). (This set will not contain the
211 * element once the call returns.)
212 *
213 * @param o object to be removed from this set, if present
214 * @return {@code true} if this set contained the specified element
215 */
216 public boolean remove(Object o) {
217 return al.remove(o);
218 }
219
220 /**
221 * Adds the specified element to this set if it is not already present.
222 * More formally, adds the specified element {@code e} to this set if
223 * the set contains no element {@code e2} such that
224 * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>.
225 * If this set already contains the element, the call leaves the set
226 * unchanged and returns {@code false}.
227 *
228 * @param e element to be added to this set
229 * @return {@code true} if this set did not already contain the specified
230 * element
231 */
232 public boolean add(E e) {
233 return al.addIfAbsent(e);
234 }
235
236 /**
237 * Returns {@code true} if this set contains all of the elements of the
238 * specified collection. If the specified collection is also a set, this
239 * method returns {@code true} if it is a <i>subset</i> of this set.
240 *
241 * @param c collection to be checked for containment in this set
242 * @return {@code true} if this set contains all of the elements of the
243 * specified collection
244 * @throws NullPointerException if the specified collection is null
245 * @see #contains(Object)
246 */
247 public boolean containsAll(Collection<?> c) {
248 return al.containsAll(c);
249 }
250
251 /**
252 * Adds all of the elements in the specified collection to this set if
253 * they're not already present. If the specified collection is also a
254 * set, the {@code addAll} operation effectively modifies this set so
255 * that its value is the <i>union</i> of the two sets. The behavior of
256 * this operation is undefined if the specified collection is modified
257 * while the operation is in progress.
258 *
259 * @param c collection containing elements to be added to this set
260 * @return {@code true} if this set changed as a result of the call
261 * @throws NullPointerException if the specified collection is null
262 * @see #add(Object)
263 */
264 public boolean addAll(Collection<? extends E> c) {
265 return al.addAllAbsent(c) > 0;
266 }
267
268 /**
269 * Removes from this set all of its elements that are contained in the
270 * specified collection. If the specified collection is also a set,
271 * this operation effectively modifies this set so that its value is the
272 * <i>asymmetric set difference</i> of the two sets.
273 *
274 * @param c collection containing elements to be removed from this set
275 * @return {@code true} if this set changed as a result of the call
276 * @throws ClassCastException if the class of an element of this set
277 * is incompatible with the specified collection (optional)
278 * @throws NullPointerException if this set contains a null element and the
279 * specified collection does not permit null elements (optional),
280 * or if the specified collection is null
281 * @see #remove(Object)
282 */
283 public boolean removeAll(Collection<?> c) {
284 return al.removeAll(c);
285 }
286
287 /**
288 * Retains only the elements in this set that are contained in the
289 * specified collection. In other words, removes from this set all of
290 * its elements that are not contained in the specified collection. If
291 * the specified collection is also a set, this operation effectively
292 * modifies this set so that its value is the <i>intersection</i> of the
293 * two sets.
294 *
295 * @param c collection containing elements to be retained in this set
296 * @return {@code true} if this set changed as a result of the call
297 * @throws ClassCastException if the class of an element of this set
298 * is incompatible with the specified collection (optional)
299 * @throws NullPointerException if this set contains a null element and the
300 * specified collection does not permit null elements (optional),
301 * or if the specified collection is null
302 * @see #remove(Object)
303 */
304 public boolean retainAll(Collection<?> c) {
305 return al.retainAll(c);
306 }
307
308 /**
309 * Returns an iterator over the elements contained in this set
310 * in the order in which these elements were added.
311 *
312 * <p>The returned iterator provides a snapshot of the state of the set
313 * when the iterator was constructed. No synchronization is needed while
314 * traversing the iterator. The iterator does <em>NOT</em> support the
315 * {@code remove} method.
316 *
317 * @return an iterator over the elements in this set
318 */
319 public Iterator<E> iterator() {
320 return al.iterator();
321 }
322
323 /**
324 * Compares the specified object with this set for equality.
325 * Returns {@code true} if the specified object is the same object
326 * as this object, or if it is also a {@link Set} and the elements
327 * returned by an {@linkplain Set#iterator() iterator} over the
328 * specified set are the same as the elements returned by an
329 * iterator over this set. More formally, the two iterators are
330 * considered to return the same elements if they return the same
331 * number of elements and for every element {@code e1} returned by
332 * the iterator over the specified set, there is an element
333 * {@code e2} returned by the iterator over this set such that
334 * {@code (e1==null ? e2==null : e1.equals(e2))}.
335 *
336 * @param o object to be compared for equality with this set
337 * @return {@code true} if the specified object is equal to this set
338 */
339 public boolean equals(Object o) {
340 if (o == this)
341 return true;
342 if (!(o instanceof Set))
343 return false;
344 Set<?> set = (Set<?>)(o);
345 Iterator<?> it = set.iterator();
346
347 // Uses O(n^2) algorithm that is only appropriate
348 // for small sets, which CopyOnWriteArraySets should be.
349
350 // Use a single snapshot of underlying array
351 Object[] elements = al.getArray();
352 int len = elements.length;
353 // Mark matched elements to avoid re-checking
354 boolean[] matched = new boolean[len];
355 int k = 0;
356 outer: while (it.hasNext()) {
357 if (++k > len)
358 return false;
359 Object x = it.next();
360 for (int i = 0; i < len; ++i) {
361 if (!matched[i] && eq(x, elements[i])) {
362 matched[i] = true;
363 continue outer;
364 }
365 }
366 return false;
367 }
368 return k == len;
369 }
370
371 public boolean removeIf(Predicate<? super E> filter) {
372 return al.removeIf(filter);
373 }
374
375 public void forEach(Consumer<? super E> action) {
376 al.forEach(action);
377 }
378
379 /**
380 * Returns a {@link Spliterator} over the elements in this set in the order
381 * in which these elements were added.
382 *
383 * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
384 * {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and
385 * {@link Spliterator#SUBSIZED}.
386 *
387 * <p>The spliterator provides a snapshot of the state of the set
388 * when the spliterator was constructed. No synchronization is needed while
389 * operating on the spliterator. The spliterator does <em>NOT</em> support
390 * the {@code remove}, {@code set} or {@code add} methods.
391 *
392 * @return a {@code Spliterator} over the elements in this set
393 * @since 1.8
394 */
395 public Spliterator<E> spliterator() {
396 return Spliterators.spliterator
397 (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT);
398 }
399
400 /**
401 * Tests for equality, coping with nulls.
402 */
403 private static boolean eq(Object o1, Object o2) {
404 return (o1 == null) ? o2 == null : o1.equals(o2);
405 }
406 }