ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.51
Committed: Wed Mar 13 12:39:02 2013 UTC (11 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.50: +1 -8 lines
Log Message:
Synch with lambda Spliterator API

File Contents

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