ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.1
Committed: Sat Mar 26 06:22:50 2016 UTC (8 years, 1 month ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Log Message:
fork jdk8 maintenance branch for source and jtreg tests

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
9 import java.util.AbstractSet;
10 import java.util.Collection;
11 import java.util.Iterator;
12 import java.util.Objects;
13 import java.util.Set;
14 import java.util.Spliterator;
15 import java.util.Spliterators;
16 import java.util.function.Consumer;
17 import java.util.function.Predicate;
18
19 /**
20 * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList}
21 * for all of its operations. Thus, it shares the same basic properties:
22 * <ul>
23 * <li>It is best suited for applications in which set sizes generally
24 * stay small, read-only operations
25 * vastly outnumber mutative operations, and you need
26 * to prevent interference among threads during traversal.
27 * <li>It is thread-safe.
28 * <li>Mutative operations ({@code add}, {@code set}, {@code remove}, etc.)
29 * are expensive since they usually entail copying the entire underlying
30 * array.
31 * <li>Iterators do not support the mutative {@code remove} operation.
32 * <li>Traversal via iterators is fast and cannot encounter
33 * interference from other threads. Iterators rely on
34 * unchanging snapshots of the array at the time the iterators were
35 * constructed.
36 * </ul>
37 *
38 * <p><b>Sample Usage.</b> The following code sketch uses a
39 * copy-on-write set to maintain a set of Handler objects that
40 * perform some action upon state updates.
41 *
42 * <pre> {@code
43 * class Handler { void handle(); ... }
44 *
45 * class X {
46 * private final CopyOnWriteArraySet<Handler> handlers
47 * = new CopyOnWriteArraySet<>();
48 * public void addHandler(Handler h) { handlers.add(h); }
49 *
50 * private long internalState;
51 * private synchronized void changeState() { internalState = ...; }
52 *
53 * public void update() {
54 * changeState();
55 * for (Handler handler : handlers)
56 * handler.handle();
57 * }
58 * }}</pre>
59 *
60 * <p>This class is a member of the
61 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
62 * Java Collections Framework</a>.
63 *
64 * @see CopyOnWriteArrayList
65 * @since 1.5
66 * @author Doug Lea
67 * @param <E> the type of elements held in this set
68 */
69 public class CopyOnWriteArraySet<E> extends AbstractSet<E>
70 implements java.io.Serializable {
71 private static final long serialVersionUID = 5457747651344034263L;
72
73 private final CopyOnWriteArrayList<E> al;
74
75 /**
76 * Creates an empty set.
77 */
78 public CopyOnWriteArraySet() {
79 al = new CopyOnWriteArrayList<E>();
80 }
81
82 /**
83 * Creates a set containing all of the elements of the specified
84 * collection.
85 *
86 * @param c the collection of elements to initially contain
87 * @throws NullPointerException if the specified collection is null
88 */
89 public CopyOnWriteArraySet(Collection<? extends E> c) {
90 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 }
100
101 /**
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 return al.size();
108 }
109
110 /**
111 * Returns {@code true} if this set contains no elements.
112 *
113 * @return {@code true} if this set contains no elements
114 */
115 public boolean isEmpty() {
116 return al.isEmpty();
117 }
118
119 /**
120 * Returns {@code true} if this set contains the specified element.
121 * More formally, returns {@code true} if and only if this set
122 * contains an element {@code e} such that {@code Objects.equals(o, e)}.
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 * {@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 *
212 * @param o object to be removed from this set, if present
213 * @return {@code true} if this set contained the specified element
214 */
215 public boolean remove(Object o) {
216 return al.remove(o);
217 }
218
219 /**
220 * Adds the specified element to this set if it is not already present.
221 * More formally, adds the specified element {@code e} to this set if
222 * the set contains no element {@code e2} such that
223 * {@code Objects.equals(e, e2)}.
224 * If this set already contains the element, the call leaves the set
225 * unchanged and returns {@code false}.
226 *
227 * @param e element to be added to this set
228 * @return {@code true} if this set did not already contain the specified
229 * element
230 */
231 public boolean add(E e) {
232 return al.addIfAbsent(e);
233 }
234
235 /**
236 * Returns {@code true} if this set contains all of the elements of the
237 * specified collection. If the specified collection is also a set, this
238 * method returns {@code true} if it is a <i>subset</i> of this set.
239 *
240 * @param c collection to be checked for containment in this set
241 * @return {@code true} if this set contains all of the elements of the
242 * specified collection
243 * @throws NullPointerException if the specified collection is null
244 * @see #contains(Object)
245 */
246 public boolean containsAll(Collection<?> c) {
247 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 }
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 * set, the {@code addAll} operation effectively modifies this set so
291 * that its value is the <i>union</i> of the two sets. The behavior of
292 * this operation is undefined if the specified collection is modified
293 * while the operation is in progress.
294 *
295 * @param c collection containing elements to be added to this set
296 * @return {@code true} if this set changed as a result of the call
297 * @throws NullPointerException if the specified collection is null
298 * @see #add(Object)
299 */
300 public boolean addAll(Collection<? extends E> c) {
301 return al.addAllAbsent(c) > 0;
302 }
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 * @return {@code true} if this set changed as a result of the call
312 * @throws ClassCastException if the class of an element of this set
313 * is incompatible with the specified collection
314 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>)
315 * @throws NullPointerException if this set contains a null element and the
316 * specified collection does not permit null elements
317 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>),
318 * or if the specified collection is null
319 * @see #remove(Object)
320 */
321 public boolean removeAll(Collection<?> c) {
322 return al.removeAll(c);
323 }
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 * @return {@code true} if this set changed as a result of the call
335 * @throws ClassCastException if the class of an element of this set
336 * is incompatible with the specified collection
337 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>)
338 * @throws NullPointerException if this set contains a null element and the
339 * specified collection does not permit null elements
340 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>),
341 * or if the specified collection is null
342 * @see #remove(Object)
343 */
344 public boolean retainAll(Collection<?> c) {
345 return al.retainAll(c);
346 }
347
348 /**
349 * Returns an iterator over the elements contained in this set
350 * in the order in which these elements were added.
351 *
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 * {@code remove} method.
356 *
357 * @return an iterator over the elements in this set
358 */
359 public Iterator<E> iterator() {
360 return al.iterator();
361 }
362
363 /**
364 * Compares the specified object with this set for equality.
365 * 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 * returned by an {@linkplain Set#iterator() iterator} over the
368 * 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 * {@code Objects.equals(e1, e2)}.
375 *
376 * @param o object to be compared for equality with this set
377 * @return {@code true} if the specified object is equal to this set
378 */
379 public boolean equals(Object o) {
380 return (o == this)
381 || ((o instanceof Set)
382 && compareSets(al.getArray(), (Set<?>) o) == 0);
383 }
384
385 public boolean removeIf(Predicate<? super E> filter) {
386 return al.removeIf(filter);
387 }
388
389 public void forEach(Consumer<? super E> action) {
390 al.forEach(action);
391 }
392
393 /**
394 * Returns a {@link Spliterator} over the elements in this set in the order
395 * in which these elements were added.
396 *
397 * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
398 * {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and
399 * {@link Spliterator#SUBSIZED}.
400 *
401 * <p>The spliterator provides a snapshot of the state of the set
402 * when the spliterator was constructed. No synchronization is needed while
403 * operating on the spliterator.
404 *
405 * @return a {@code Spliterator} over the elements in this set
406 * @since 1.8
407 */
408 public Spliterator<E> spliterator() {
409 return Spliterators.spliterator
410 (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT);
411 }
412 }