ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.63
Committed: Fri Jan 2 07:42:41 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.62: +1 -1 lines
Log Message:
remove redundant parens

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 jsr166 1.61
9     import java.util.AbstractSet;
10 dl 1.45 import java.util.Collection;
11 jsr166 1.61 import java.util.Iterator;
12 dl 1.45 import java.util.Set;
13     import java.util.Spliterator;
14 dl 1.50 import java.util.Spliterators;
15 jsr166 1.61 import java.util.function.Consumer;
16 dl 1.54 import java.util.function.Predicate;
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 jsr166 1.57 * = new CopyOnWriteArraySet<>();
47 jsr166 1.37 * 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 jsr166 1.60 * @param <E> the type of elements held in this set
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 dl 1.54 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 tim 1.1 }
99    
100 jsr166 1.26 /**
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 jsr166 1.36 return al.size();
107 jsr166 1.26 }
108    
109     /**
110 jsr166 1.44 * Returns {@code true} if this set contains no elements.
111 jsr166 1.26 *
112 jsr166 1.44 * @return {@code true} if this set contains no elements
113 jsr166 1.26 */
114     public boolean isEmpty() {
115 jsr166 1.36 return al.isEmpty();
116 jsr166 1.26 }
117    
118     /**
119 jsr166 1.44 * Returns {@code true} if this set contains the specified element.
120     * More formally, returns {@code true} if and only if this set
121 jsr166 1.58 * contains an element {@code e} such that {@code Objects.equals(o, e)}.
122 jsr166 1.26 *
123     * @param o element whose presence in this set is to be tested
124 jsr166 1.44 * @return {@code true} if this set contains the specified element
125 jsr166 1.26 */
126     public boolean contains(Object o) {
127 jsr166 1.36 return al.contains(o);
128 jsr166 1.26 }
129    
130     /**
131     * Returns an array containing all of the elements in this set.
132     * If this set makes any guarantees as to what order its elements
133     * are returned by its iterator, this method must return the
134     * elements in the same order.
135     *
136     * <p>The returned array will be "safe" in that no references to it
137     * are maintained by this set. (In other words, this method must
138     * allocate a new array even if this set is backed by an array).
139     * The caller is thus free to modify the returned array.
140     *
141     * <p>This method acts as bridge between array-based and collection-based
142     * APIs.
143     *
144     * @return an array containing all the elements in this set
145     */
146     public Object[] toArray() {
147 jsr166 1.36 return al.toArray();
148 jsr166 1.26 }
149    
150     /**
151     * Returns an array containing all of the elements in this set; the
152     * runtime type of the returned array is that of the specified array.
153     * If the set fits in the specified array, it is returned therein.
154     * Otherwise, a new array is allocated with the runtime type of the
155     * specified array and the size of this set.
156     *
157     * <p>If this set fits in the specified array with room to spare
158     * (i.e., the array has more elements than this set), the element in
159     * the array immediately following the end of the set is set to
160 jsr166 1.44 * {@code null}. (This is useful in determining the length of this
161 jsr166 1.26 * set <i>only</i> if the caller knows that this set does not contain
162     * any null elements.)
163     *
164     * <p>If this set makes any guarantees as to what order its elements
165     * are returned by its iterator, this method must return the elements
166     * in the same order.
167     *
168     * <p>Like the {@link #toArray()} method, this method acts as bridge between
169     * array-based and collection-based APIs. Further, this method allows
170     * precise control over the runtime type of the output array, and may,
171     * under certain circumstances, be used to save allocation costs.
172     *
173 jsr166 1.44 * <p>Suppose {@code x} is a set known to contain only strings.
174 jsr166 1.26 * The following code can be used to dump the set into a newly allocated
175 jsr166 1.44 * array of {@code String}:
176 jsr166 1.26 *
177 jsr166 1.40 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
178 jsr166 1.26 *
179 jsr166 1.44 * Note that {@code toArray(new Object[0])} is identical in function to
180     * {@code toArray()}.
181 jsr166 1.26 *
182     * @param a the array into which the elements of this set are to be
183     * stored, if it is big enough; otherwise, a new array of the same
184     * runtime type is allocated for this purpose.
185     * @return an array containing all the elements in this set
186     * @throws ArrayStoreException if the runtime type of the specified array
187     * is not a supertype of the runtime type of every element in this
188     * set
189     * @throws NullPointerException if the specified array is null
190     */
191     public <T> T[] toArray(T[] a) {
192 jsr166 1.36 return al.toArray(a);
193 jsr166 1.26 }
194    
195     /**
196     * Removes all of the elements from this set.
197 jsr166 1.27 * The set will be empty after this call returns.
198 jsr166 1.26 */
199     public void clear() {
200     al.clear();
201     }
202    
203     /**
204     * Removes the specified element from this set if it is present.
205 jsr166 1.44 * More formally, removes an element {@code e} such that
206 jsr166 1.58 * {@code Objects.equals(o, e)}, if this set contains such an element.
207     * Returns {@code true} if this set contained the element (or
208     * equivalently, if this set changed as a result of the call).
209     * (This set will not contain the element once the call returns.)
210 jsr166 1.26 *
211     * @param o object to be removed from this set, if present
212 jsr166 1.44 * @return {@code true} if this set contained the specified element
213 jsr166 1.26 */
214     public boolean remove(Object o) {
215 jsr166 1.36 return al.remove(o);
216 jsr166 1.26 }
217    
218     /**
219     * Adds the specified element to this set if it is not already present.
220 jsr166 1.44 * More formally, adds the specified element {@code e} to this set if
221     * the set contains no element {@code e2} such that
222 jsr166 1.58 * {@code Objects.equals(e, e2)}.
223 jsr166 1.28 * If this set already contains the element, the call leaves the set
224 jsr166 1.44 * unchanged and returns {@code false}.
225 jsr166 1.26 *
226     * @param e element to be added to this set
227 jsr166 1.44 * @return {@code true} if this set did not already contain the specified
228 jsr166 1.26 * element
229     */
230     public boolean add(E e) {
231 jsr166 1.36 return al.addIfAbsent(e);
232 jsr166 1.26 }
233 tim 1.1
234 jsr166 1.26 /**
235 jsr166 1.44 * Returns {@code true} if this set contains all of the elements of the
236 jsr166 1.26 * specified collection. If the specified collection is also a set, this
237 jsr166 1.44 * method returns {@code true} if it is a <i>subset</i> of this set.
238 jsr166 1.26 *
239     * @param c collection to be checked for containment in this set
240 jsr166 1.44 * @return {@code true} if this set contains all of the elements of the
241 jsr166 1.36 * specified collection
242 jsr166 1.26 * @throws NullPointerException if the specified collection is null
243     * @see #contains(Object)
244     */
245     public boolean containsAll(Collection<?> c) {
246 jsr166 1.36 return al.containsAll(c);
247 jsr166 1.26 }
248    
249     /**
250     * Adds all of the elements in the specified collection to this set if
251     * they're not already present. If the specified collection is also a
252 jsr166 1.44 * set, the {@code addAll} operation effectively modifies this set so
253 jsr166 1.26 * that its value is the <i>union</i> of the two sets. The behavior of
254 jsr166 1.28 * this operation is undefined if the specified collection is modified
255 jsr166 1.26 * while the operation is in progress.
256     *
257     * @param c collection containing elements to be added to this set
258 jsr166 1.44 * @return {@code true} if this set changed as a result of the call
259 jsr166 1.26 * @throws NullPointerException if the specified collection is null
260     * @see #add(Object)
261     */
262     public boolean addAll(Collection<? extends E> c) {
263 dl 1.52 return al.addAllAbsent(c) > 0;
264 jsr166 1.26 }
265    
266     /**
267     * Removes from this set all of its elements that are contained in the
268     * specified collection. If the specified collection is also a set,
269     * this operation effectively modifies this set so that its value is the
270     * <i>asymmetric set difference</i> of the two sets.
271     *
272     * @param c collection containing elements to be removed from this set
273 jsr166 1.44 * @return {@code true} if this set changed as a result of the call
274 jsr166 1.26 * @throws ClassCastException if the class of an element of this set
275     * is incompatible with the specified collection (optional)
276     * @throws NullPointerException if this set contains a null element and the
277     * specified collection does not permit null elements (optional),
278     * or if the specified collection is null
279     * @see #remove(Object)
280     */
281     public boolean removeAll(Collection<?> c) {
282 jsr166 1.36 return al.removeAll(c);
283 jsr166 1.26 }
284    
285     /**
286     * Retains only the elements in this set that are contained in the
287     * specified collection. In other words, removes from this set all of
288     * its elements that are not contained in the specified collection. If
289     * the specified collection is also a set, this operation effectively
290     * modifies this set so that its value is the <i>intersection</i> of the
291     * two sets.
292     *
293     * @param c collection containing elements to be retained in this set
294 jsr166 1.44 * @return {@code true} if this set changed as a result of the call
295 jsr166 1.26 * @throws ClassCastException if the class of an element of this set
296     * is incompatible with the specified collection (optional)
297     * @throws NullPointerException if this set contains a null element and the
298     * specified collection does not permit null elements (optional),
299     * or if the specified collection is null
300     * @see #remove(Object)
301     */
302     public boolean retainAll(Collection<?> c) {
303 jsr166 1.36 return al.retainAll(c);
304 jsr166 1.26 }
305 tim 1.1
306 dl 1.20 /**
307 jsr166 1.24 * Returns an iterator over the elements contained in this set
308 dl 1.20 * in the order in which these elements were added.
309 jsr166 1.26 *
310     * <p>The returned iterator provides a snapshot of the state of the set
311     * when the iterator was constructed. No synchronization is needed while
312     * traversing the iterator. The iterator does <em>NOT</em> support the
313 jsr166 1.44 * {@code remove} method.
314 jsr166 1.26 *
315     * @return an iterator over the elements in this set
316 dl 1.20 */
317 jsr166 1.26 public Iterator<E> iterator() {
318 jsr166 1.36 return al.iterator();
319 jsr166 1.26 }
320 dl 1.20
321 dl 1.30 /**
322     * Compares the specified object with this set for equality.
323 jsr166 1.33 * Returns {@code true} if the specified object is the same object
324     * as this object, or if it is also a {@link Set} and the elements
325 jsr166 1.47 * returned by an {@linkplain Set#iterator() iterator} over the
326 jsr166 1.33 * specified set are the same as the elements returned by an
327     * iterator over this set. More formally, the two iterators are
328     * considered to return the same elements if they return the same
329     * number of elements and for every element {@code e1} returned by
330     * the iterator over the specified set, there is an element
331     * {@code e2} returned by the iterator over this set such that
332 jsr166 1.59 * {@code Objects.equals(e1, e2)}.
333 dl 1.30 *
334     * @param o object to be compared for equality with this set
335 jsr166 1.33 * @return {@code true} if the specified object is equal to this set
336 dl 1.30 */
337     public boolean equals(Object o) {
338     if (o == this)
339     return true;
340     if (!(o instanceof Set))
341     return false;
342 jsr166 1.63 Set<?> set = (Set<?>)o;
343 jsr166 1.36 Iterator<?> it = set.iterator();
344 dl 1.30
345     // Uses O(n^2) algorithm that is only appropriate
346     // for small sets, which CopyOnWriteArraySets should be.
347    
348     // Use a single snapshot of underlying array
349 jsr166 1.36 Object[] elements = al.getArray();
350     int len = elements.length;
351 dl 1.30 // Mark matched elements to avoid re-checking
352     boolean[] matched = new boolean[len];
353     int k = 0;
354 jsr166 1.33 outer: while (it.hasNext()) {
355 dl 1.30 if (++k > len)
356     return false;
357 jsr166 1.33 Object x = it.next();
358 dl 1.30 for (int i = 0; i < len; ++i) {
359     if (!matched[i] && eq(x, elements[i])) {
360     matched[i] = true;
361 jsr166 1.36 continue outer;
362 dl 1.30 }
363     }
364 jsr166 1.36 return false;
365 dl 1.30 }
366     return k == len;
367     }
368 jsr166 1.32
369 dl 1.54 public boolean removeIf(Predicate<? super E> filter) {
370     return al.removeIf(filter);
371     }
372    
373     public void forEach(Consumer<? super E> action) {
374     al.forEach(action);
375     }
376    
377 jsr166 1.56 /**
378     * Returns a {@link Spliterator} over the elements in this set in the order
379     * in which these elements were added.
380     *
381     * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
382     * {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and
383     * {@link Spliterator#SUBSIZED}.
384     *
385     * <p>The spliterator provides a snapshot of the state of the set
386     * when the spliterator was constructed. No synchronization is needed while
387     * operating on the spliterator. The spliterator does <em>NOT</em> support
388     * the {@code remove}, {@code set} or {@code add} methods.
389     *
390     * @return a {@code Spliterator} over the elements in this set
391     * @since 1.8
392     */
393 dl 1.51 public Spliterator<E> spliterator() {
394 dl 1.50 return Spliterators.spliterator
395 dl 1.55 (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT);
396 dl 1.48 }
397    
398 dl 1.30 /**
399 jsr166 1.41 * Tests for equality, coping with nulls.
400 dl 1.30 */
401     private static boolean eq(Object o1, Object o2) {
402 jsr166 1.39 return (o1 == null) ? o2 == null : o1.equals(o2);
403 dl 1.30 }
404 tim 1.1 }