ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.46
Committed: Wed Jan 16 21:18:51 2013 UTC (11 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.45: +2 -2 lines
Log Message:
whitespace

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