ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.75
Committed: Fri Nov 27 17:41:59 2020 UTC (3 years, 6 months ago) by dl
Branch: MAIN
CVS Tags: HEAD
Changes since 1.74: +1 -1 lines
Log Message:
Incorporate snippets code improvements from Pavel Rappo

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 jsr166 1.65 import java.util.Objects;
13 dl 1.45 import java.util.Set;
14     import java.util.Spliterator;
15 dl 1.50 import java.util.Spliterators;
16 jsr166 1.61 import java.util.function.Consumer;
17 dl 1.54 import java.util.function.Predicate;
18 tim 1.1
19     /**
20 jsr166 1.72 * A {@link Set} that uses an internal {@link CopyOnWriteArrayList}
21 jsr166 1.26 * for all of its operations. Thus, it shares the same basic properties:
22 tim 1.1 * <ul>
23 dholmes 1.7 * <li>It is best suited for applications in which set sizes generally
24 tim 1.1 * stay small, read-only operations
25     * vastly outnumber mutative operations, and you need
26     * to prevent interference among threads during traversal.
27 dl 1.16 * <li>It is thread-safe.
28 jsr166 1.44 * <li>Mutative operations ({@code add}, {@code set}, {@code remove}, etc.)
29 jsr166 1.26 * are expensive since they usually entail copying the entire underlying
30     * array.
31 jsr166 1.44 * <li>Iterators do not support the mutative {@code remove} operation.
32 dl 1.18 * <li>Traversal via iterators is fast and cannot encounter
33 tim 1.1 * interference from other threads. Iterators rely on
34     * unchanging snapshots of the array at the time the iterators were
35 jsr166 1.26 * constructed.
36 tim 1.1 * </ul>
37 dl 1.18 *
38 jsr166 1.42 * <p><b>Sample Usage.</b> The following code sketch uses a
39 jsr166 1.21 * copy-on-write set to maintain a set of Handler objects that
40     * perform some action upon state updates.
41 dl 1.18 *
42 jsr166 1.64 * <pre> {@code
43 dl 1.75 * class Handler { void handle() { ... } }
44 tim 1.1 *
45     * class X {
46 jsr166 1.37 * private final CopyOnWriteArraySet<Handler> handlers
47 jsr166 1.57 * = new CopyOnWriteArraySet<>();
48 jsr166 1.37 * public void addHandler(Handler h) { handlers.add(h); }
49 tim 1.1 *
50 jsr166 1.37 * private long internalState;
51     * private synchronized void changeState() { internalState = ...; }
52 tim 1.1 *
53 jsr166 1.37 * public void update() {
54     * changeState();
55     * for (Handler handler : handlers)
56 jsr166 1.43 * handler.handle();
57 jsr166 1.37 * }
58     * }}</pre>
59 dl 1.14 *
60     * <p>This class is a member of the
61 jsr166 1.74 * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
62 dl 1.14 * Java Collections Framework</a>.
63     *
64 dl 1.16 * @see CopyOnWriteArrayList
65 dl 1.4 * @since 1.5
66     * @author Doug Lea
67 jsr166 1.60 * @param <E> the type of elements held in this set
68 dl 1.4 */
69 tim 1.1 public class CopyOnWriteArraySet<E> extends AbstractSet<E>
70 dl 1.18 implements java.io.Serializable {
71 dl 1.8 private static final long serialVersionUID = 5457747651344034263L;
72 tim 1.1
73     private final CopyOnWriteArrayList<E> al;
74    
75     /**
76 dl 1.15 * Creates an empty set.
77 tim 1.1 */
78     public CopyOnWriteArraySet() {
79     al = new CopyOnWriteArrayList<E>();
80     }
81    
82     /**
83 dl 1.15 * Creates a set containing all of the elements of the specified
84 jsr166 1.23 * collection.
85 jsr166 1.25 *
86 jsr166 1.23 * @param c the collection of elements to initially contain
87     * @throws NullPointerException if the specified collection is null
88 tim 1.1 */
89 tim 1.12 public CopyOnWriteArraySet(Collection<? extends E> c) {
90 dl 1.54 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 tim 1.1 }
100    
101 jsr166 1.26 /**
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 jsr166 1.36 return al.size();
108 jsr166 1.26 }
109    
110     /**
111 jsr166 1.44 * Returns {@code true} if this set contains no elements.
112 jsr166 1.26 *
113 jsr166 1.44 * @return {@code true} if this set contains no elements
114 jsr166 1.26 */
115     public boolean isEmpty() {
116 jsr166 1.36 return al.isEmpty();
117 jsr166 1.26 }
118    
119     /**
120 jsr166 1.44 * Returns {@code true} if this set contains the specified element.
121     * More formally, returns {@code true} if and only if this set
122 jsr166 1.58 * contains an element {@code e} such that {@code Objects.equals(o, e)}.
123 jsr166 1.26 *
124     * @param o element whose presence in this set is to be tested
125 jsr166 1.44 * @return {@code true} if this set contains the specified element
126 jsr166 1.26 */
127     public boolean contains(Object o) {
128 jsr166 1.36 return al.contains(o);
129 jsr166 1.26 }
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 jsr166 1.36 return al.toArray();
149 jsr166 1.26 }
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 jsr166 1.44 * {@code null}. (This is useful in determining the length of this
162 jsr166 1.26 * 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 jsr166 1.44 * <p>Suppose {@code x} is a set known to contain only strings.
175 jsr166 1.26 * The following code can be used to dump the set into a newly allocated
176 jsr166 1.44 * array of {@code String}:
177 jsr166 1.26 *
178 jsr166 1.64 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
179 jsr166 1.26 *
180 jsr166 1.44 * Note that {@code toArray(new Object[0])} is identical in function to
181     * {@code toArray()}.
182 jsr166 1.26 *
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 jsr166 1.36 return al.toArray(a);
194 jsr166 1.26 }
195    
196     /**
197     * Removes all of the elements from this set.
198 jsr166 1.27 * The set will be empty after this call returns.
199 jsr166 1.26 */
200     public void clear() {
201     al.clear();
202     }
203    
204     /**
205     * Removes the specified element from this set if it is present.
206 jsr166 1.44 * More formally, removes an element {@code e} such that
207 jsr166 1.58 * {@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 jsr166 1.26 *
212     * @param o object to be removed from this set, if present
213 jsr166 1.44 * @return {@code true} if this set contained the specified element
214 jsr166 1.26 */
215     public boolean remove(Object o) {
216 jsr166 1.36 return al.remove(o);
217 jsr166 1.26 }
218    
219     /**
220     * Adds the specified element to this set if it is not already present.
221 jsr166 1.44 * More formally, adds the specified element {@code e} to this set if
222     * the set contains no element {@code e2} such that
223 jsr166 1.58 * {@code Objects.equals(e, e2)}.
224 jsr166 1.28 * If this set already contains the element, the call leaves the set
225 jsr166 1.44 * unchanged and returns {@code false}.
226 jsr166 1.26 *
227     * @param e element to be added to this set
228 jsr166 1.44 * @return {@code true} if this set did not already contain the specified
229 jsr166 1.26 * element
230     */
231     public boolean add(E e) {
232 jsr166 1.36 return al.addIfAbsent(e);
233 jsr166 1.26 }
234 tim 1.1
235 jsr166 1.26 /**
236 jsr166 1.44 * Returns {@code true} if this set contains all of the elements of the
237 jsr166 1.26 * specified collection. If the specified collection is also a set, this
238 jsr166 1.44 * method returns {@code true} if it is a <i>subset</i> of this set.
239 jsr166 1.26 *
240     * @param c collection to be checked for containment in this set
241 jsr166 1.44 * @return {@code true} if this set contains all of the elements of the
242 jsr166 1.36 * specified collection
243 jsr166 1.26 * @throws NullPointerException if the specified collection is null
244     * @see #contains(Object)
245     */
246     public boolean containsAll(Collection<?> c) {
247 jsr166 1.66 return (c instanceof Set)
248     ? compareSets(al.getArray(), (Set<?>) c) >= 0
249     : al.containsAll(c);
250     }
251    
252     /**
253     * Tells whether the objects in snapshot (regarded as a set) are a
254     * superset of the given set.
255     *
256     * @return -1 if snapshot is not a superset, 0 if the two sets
257     * contain precisely the same elements, and 1 if snapshot is a
258     * proper superset of the given set
259     */
260     private static int compareSets(Object[] snapshot, Set<?> set) {
261     // Uses O(n^2) algorithm, that is only appropriate for small
262     // sets, which CopyOnWriteArraySets should be.
263     //
264     // Optimize up to O(n) if the two sets share a long common prefix,
265     // as might happen if one set was created as a copy of the other set.
266    
267     final int len = snapshot.length;
268     // Mark matched elements to avoid re-checking
269     final boolean[] matched = new boolean[len];
270    
271     // j is the largest int with matched[i] true for { i | 0 <= i < j }
272     int j = 0;
273     outer: for (Object x : set) {
274     for (int i = j; i < len; i++) {
275     if (!matched[i] && Objects.equals(x, snapshot[i])) {
276     matched[i] = true;
277     if (i == j)
278     do { j++; } while (j < len && matched[j]);
279     continue outer;
280     }
281     }
282     return -1;
283     }
284     return (j == len) ? 0 : 1;
285 jsr166 1.26 }
286    
287     /**
288     * Adds all of the elements in the specified collection to this set if
289     * they're not already present. If the specified collection is also a
290 jsr166 1.44 * set, the {@code addAll} operation effectively modifies this set so
291 jsr166 1.26 * that its value is the <i>union</i> of the two sets. The behavior of
292 jsr166 1.28 * this operation is undefined if the specified collection is modified
293 jsr166 1.26 * while the operation is in progress.
294     *
295     * @param c collection containing elements to be added to this set
296 jsr166 1.44 * @return {@code true} if this set changed as a result of the call
297 jsr166 1.26 * @throws NullPointerException if the specified collection is null
298     * @see #add(Object)
299     */
300     public boolean addAll(Collection<? extends E> c) {
301 dl 1.52 return al.addAllAbsent(c) > 0;
302 jsr166 1.26 }
303    
304     /**
305     * Removes from this set all of its elements that are contained in the
306     * specified collection. If the specified collection is also a set,
307     * this operation effectively modifies this set so that its value is the
308     * <i>asymmetric set difference</i> of the two sets.
309     *
310     * @param c collection containing elements to be removed from this set
311 jsr166 1.44 * @return {@code true} if this set changed as a result of the call
312 jsr166 1.26 * @throws ClassCastException if the class of an element of this set
313 jsr166 1.67 * is incompatible with the specified collection
314 jsr166 1.74 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
315 jsr166 1.26 * @throws NullPointerException if this set contains a null element and the
316 jsr166 1.67 * specified collection does not permit null elements
317 jsr166 1.74 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>),
318 jsr166 1.26 * or if the specified collection is null
319     * @see #remove(Object)
320     */
321     public boolean removeAll(Collection<?> c) {
322 jsr166 1.36 return al.removeAll(c);
323 jsr166 1.26 }
324    
325     /**
326     * Retains only the elements in this set that are contained in the
327     * specified collection. In other words, removes from this set all of
328     * its elements that are not contained in the specified collection. If
329     * the specified collection is also a set, this operation effectively
330     * modifies this set so that its value is the <i>intersection</i> of the
331     * two sets.
332     *
333     * @param c collection containing elements to be retained in this set
334 jsr166 1.44 * @return {@code true} if this set changed as a result of the call
335 jsr166 1.69 * @throws ClassCastException if the class of an element of this set
336     * is incompatible with the specified collection
337 jsr166 1.74 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
338 jsr166 1.69 * @throws NullPointerException if this set contains a null element and the
339     * specified collection does not permit null elements
340 jsr166 1.74 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>),
341 jsr166 1.26 * or if the specified collection is null
342     * @see #remove(Object)
343     */
344     public boolean retainAll(Collection<?> c) {
345 jsr166 1.36 return al.retainAll(c);
346 jsr166 1.26 }
347 tim 1.1
348 dl 1.20 /**
349 jsr166 1.24 * Returns an iterator over the elements contained in this set
350 dl 1.20 * in the order in which these elements were added.
351 jsr166 1.26 *
352     * <p>The returned iterator provides a snapshot of the state of the set
353     * when the iterator was constructed. No synchronization is needed while
354     * traversing the iterator. The iterator does <em>NOT</em> support the
355 jsr166 1.44 * {@code remove} method.
356 jsr166 1.26 *
357     * @return an iterator over the elements in this set
358 dl 1.20 */
359 jsr166 1.26 public Iterator<E> iterator() {
360 jsr166 1.36 return al.iterator();
361 jsr166 1.26 }
362 dl 1.20
363 dl 1.30 /**
364     * Compares the specified object with this set for equality.
365 jsr166 1.33 * Returns {@code true} if the specified object is the same object
366     * as this object, or if it is also a {@link Set} and the elements
367 jsr166 1.47 * returned by an {@linkplain Set#iterator() iterator} over the
368 jsr166 1.33 * specified set are the same as the elements returned by an
369     * iterator over this set. More formally, the two iterators are
370     * considered to return the same elements if they return the same
371     * number of elements and for every element {@code e1} returned by
372     * the iterator over the specified set, there is an element
373     * {@code e2} returned by the iterator over this set such that
374 jsr166 1.59 * {@code Objects.equals(e1, e2)}.
375 dl 1.30 *
376     * @param o object to be compared for equality with this set
377 jsr166 1.33 * @return {@code true} if the specified object is equal to this set
378 dl 1.30 */
379     public boolean equals(Object o) {
380 jsr166 1.66 return (o == this)
381     || ((o instanceof Set)
382     && compareSets(al.getArray(), (Set<?>) o) == 0);
383 dl 1.30 }
384 jsr166 1.32
385 jsr166 1.71 /**
386     * @throws NullPointerException {@inheritDoc}
387     */
388 dl 1.54 public boolean removeIf(Predicate<? super E> filter) {
389     return al.removeIf(filter);
390     }
391    
392 jsr166 1.71 /**
393     * @throws NullPointerException {@inheritDoc}
394     */
395 dl 1.54 public void forEach(Consumer<? super E> action) {
396     al.forEach(action);
397     }
398    
399 jsr166 1.56 /**
400     * Returns a {@link Spliterator} over the elements in this set in the order
401     * in which these elements were added.
402     *
403     * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
404     * {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and
405     * {@link Spliterator#SUBSIZED}.
406     *
407     * <p>The spliterator provides a snapshot of the state of the set
408     * when the spliterator was constructed. No synchronization is needed while
409 jsr166 1.68 * operating on the spliterator.
410 jsr166 1.56 *
411     * @return a {@code Spliterator} over the elements in this set
412     * @since 1.8
413     */
414 dl 1.51 public Spliterator<E> spliterator() {
415 dl 1.50 return Spliterators.spliterator
416 dl 1.55 (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT);
417 dl 1.48 }
418 tim 1.1 }