ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArraySet.java
Revision: 1.43
Committed: Sun Nov 25 21:48:00 2012 UTC (11 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.42: +1 -1 lines
Log Message:
whitespace

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