001 /*
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
003 *
004 * This code is free software; you can redistribute it and/or modify it
005 * under the terms of the GNU General Public License version 2 only, as
006 * published by the Free Software Foundation. Sun designates this
007 * particular file as subject to the "Classpath" exception as provided
008 * by Sun in the LICENSE file that accompanied this code.
009 *
010 * This code is distributed in the hope that it will be useful, but WITHOUT
011 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
012 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
013 * version 2 for more details (a copy is included in the LICENSE file that
014 * accompanied this code).
015 *
016 * You should have received a copy of the GNU General Public License version
017 * 2 along with this work; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
019 *
020 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
021 * CA 95054 USA or visit www.sun.com if you need additional information or
022 * have any questions.
023 */
024
025 /*
026 * This file is available under and governed by the GNU General Public
027 * License version 2 only, as published by the Free Software Foundation.
028 * However, the following notice accompanied the original version of this
029 * file:
030 *
031 * Written by Doug Lea with assistance from members of JCP JSR-166
032 * Expert Group and released to the public domain, as explained at
033 * http://creativecommons.org/licenses/publicdomain
034 */
035
036 package java.util.concurrent;
037
038 import java.util.*;
039
040 /**
041 * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList}
042 * for all of its operations. Thus, it shares the same basic properties:
043 * <ul>
044 * <li>It is best suited for applications in which set sizes generally
045 * stay small, read-only operations
046 * vastly outnumber mutative operations, and you need
047 * to prevent interference among threads during traversal.
048 * <li>It is thread-safe.
049 * <li>Mutative operations (<tt>add</tt>, <tt>set</tt>, <tt>remove</tt>, etc.)
050 * are expensive since they usually entail copying the entire underlying
051 * array.
052 * <li>Iterators do not support the mutative <tt>remove</tt> operation.
053 * <li>Traversal via iterators is fast and cannot encounter
054 * interference from other threads. Iterators rely on
055 * unchanging snapshots of the array at the time the iterators were
056 * constructed.
057 * </ul>
058 *
059 * <p> <b>Sample Usage.</b> The following code sketch uses a
060 * copy-on-write set to maintain a set of Handler objects that
061 * perform some action upon state updates.
062 *
063 * <pre>
064 * class Handler { void handle(); ... }
065 *
066 * class X {
067 * private final CopyOnWriteArraySet<Handler> handlers
068 * = new CopyOnWriteArraySet<Handler>();
069 * public void addHandler(Handler h) { handlers.add(h); }
070 *
071 * private long internalState;
072 * private synchronized void changeState() { internalState = ...; }
073 *
074 * public void update() {
075 * changeState();
076 * for (Handler handler : handlers)
077 * handler.handle();
078 * }
079 * }
080 * </pre>
081 *
082 * <p>This class is a member of the
083 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
084 * Java Collections Framework</a>.
085 *
086 * @see CopyOnWriteArrayList
087 * @since 1.5
088 * @author Doug Lea
089 * @param <E> the type of elements held in this collection
090 */
091 public class CopyOnWriteArraySet<E> extends AbstractSet<E> implements
092 java.io.Serializable {
093 private static final long serialVersionUID = 5457747651344034263L;
094
095 private final CopyOnWriteArrayList<E> al;
096
097 /**
098 * Creates an empty set.
099 */
100 public CopyOnWriteArraySet() {
101 al = new CopyOnWriteArrayList<E>();
102 }
103
104 /**
105 * Creates a set containing all of the elements of the specified
106 * collection.
107 *
108 * @param c the collection of elements to initially contain
109 * @throws NullPointerException if the specified collection is null
110 */
111 public CopyOnWriteArraySet(Collection<? extends E> c) {
112 al = new CopyOnWriteArrayList<E>();
113 al.addAllAbsent(c);
114 }
115
116 /**
117 * Returns the number of elements in this set.
118 *
119 * @return the number of elements in this set
120 */
121 public int size() {
122 return al.size();
123 }
124
125 /**
126 * Returns <tt>true</tt> if this set contains no elements.
127 *
128 * @return <tt>true</tt> if this set contains no elements
129 */
130 public boolean isEmpty() {
131 return al.isEmpty();
132 }
133
134 /**
135 * Returns <tt>true</tt> if this set contains the specified element.
136 * More formally, returns <tt>true</tt> if and only if this set
137 * contains an element <tt>e</tt> such that
138 * <tt>(o==null ? e==null : o.equals(e))</tt>.
139 *
140 * @param o element whose presence in this set is to be tested
141 * @return <tt>true</tt> if this set contains the specified element
142 */
143 public boolean contains(Object o) {
144 return al.contains(o);
145 }
146
147 /**
148 * Returns an array containing all of the elements in this set.
149 * If this set makes any guarantees as to what order its elements
150 * are returned by its iterator, this method must return the
151 * elements in the same order.
152 *
153 * <p>The returned array will be "safe" in that no references to it
154 * are maintained by this set. (In other words, this method must
155 * allocate a new array even if this set is backed by an array).
156 * The caller is thus free to modify the returned array.
157 *
158 * <p>This method acts as bridge between array-based and collection-based
159 * APIs.
160 *
161 * @return an array containing all the elements in this set
162 */
163 public Object[] toArray() {
164 return al.toArray();
165 }
166
167 /**
168 * Returns an array containing all of the elements in this set; the
169 * runtime type of the returned array is that of the specified array.
170 * If the set fits in the specified array, it is returned therein.
171 * Otherwise, a new array is allocated with the runtime type of the
172 * specified array and the size of this set.
173 *
174 * <p>If this set fits in the specified array with room to spare
175 * (i.e., the array has more elements than this set), the element in
176 * the array immediately following the end of the set is set to
177 * <tt>null</tt>. (This is useful in determining the length of this
178 * set <i>only</i> if the caller knows that this set does not contain
179 * any null elements.)
180 *
181 * <p>If this set makes any guarantees as to what order its elements
182 * are returned by its iterator, this method must return the elements
183 * in the same order.
184 *
185 * <p>Like the {@link #toArray()} method, this method acts as bridge between
186 * array-based and collection-based APIs. Further, this method allows
187 * precise control over the runtime type of the output array, and may,
188 * under certain circumstances, be used to save allocation costs.
189 *
190 * <p>Suppose <tt>x</tt> is a set known to contain only strings.
191 * The following code can be used to dump the set into a newly allocated
192 * array of <tt>String</tt>:
193 *
194 * <pre>
195 * String[] y = x.toArray(new String[0]);</pre>
196 *
197 * Note that <tt>toArray(new Object[0])</tt> is identical in function to
198 * <tt>toArray()</tt>.
199 *
200 * @param a the array into which the elements of this set are to be
201 * stored, if it is big enough; otherwise, a new array of the same
202 * runtime type is allocated for this purpose.
203 * @return an array containing all the elements in this set
204 * @throws ArrayStoreException if the runtime type of the specified array
205 * is not a supertype of the runtime type of every element in this
206 * set
207 * @throws NullPointerException if the specified array is null
208 */
209 public <T> T[] toArray(T[] a) {
210 return al.toArray(a);
211 }
212
213 /**
214 * Removes all of the elements from this set.
215 * The set will be empty after this call returns.
216 */
217 public void clear() {
218 al.clear();
219 }
220
221 /**
222 * Removes the specified element from this set if it is present.
223 * More formally, removes an element <tt>e</tt> such that
224 * <tt>(o==null ? e==null : o.equals(e))</tt>,
225 * if this set contains such an element. Returns <tt>true</tt> if
226 * this set contained the element (or equivalently, if this set
227 * changed as a result of the call). (This set will not contain the
228 * element once the call returns.)
229 *
230 * @param o object to be removed from this set, if present
231 * @return <tt>true</tt> if this set contained the specified element
232 */
233 public boolean remove(Object o) {
234 return al.remove(o);
235 }
236
237 /**
238 * Adds the specified element to this set if it is not already present.
239 * More formally, adds the specified element <tt>e</tt> to this set if
240 * the set contains no element <tt>e2</tt> such that
241 * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
242 * If this set already contains the element, the call leaves the set
243 * unchanged and returns <tt>false</tt>.
244 *
245 * @param e element to be added to this set
246 * @return <tt>true</tt> if this set did not already contain the specified
247 * element
248 */
249 public boolean add(E e) {
250 return al.addIfAbsent(e);
251 }
252
253 /**
254 * Returns <tt>true</tt> if this set contains all of the elements of the
255 * specified collection. If the specified collection is also a set, this
256 * method returns <tt>true</tt> if it is a <i>subset</i> of this set.
257 *
258 * @param c collection to be checked for containment in this set
259 * @return <tt>true</tt> if this set contains all of the elements of the
260 * specified collection
261 * @throws NullPointerException if the specified collection is null
262 * @see #contains(Object)
263 */
264 public boolean containsAll(Collection<?> c) {
265 return al.containsAll(c);
266 }
267
268 /**
269 * Adds all of the elements in the specified collection to this set if
270 * they're not already present. If the specified collection is also a
271 * set, the <tt>addAll</tt> operation effectively modifies this set so
272 * that its value is the <i>union</i> of the two sets. The behavior of
273 * this operation is undefined if the specified collection is modified
274 * while the operation is in progress.
275 *
276 * @param c collection containing elements to be added to this set
277 * @return <tt>true</tt> if this set changed as a result of the call
278 * @throws NullPointerException if the specified collection is null
279 * @see #add(Object)
280 */
281 public boolean addAll(Collection<? extends E> c) {
282 return al.addAllAbsent(c) > 0;
283 }
284
285 /**
286 * Removes from this set all of its elements that are contained in the
287 * specified collection. If the specified collection is also a set,
288 * this operation effectively modifies this set so that its value is the
289 * <i>asymmetric set difference</i> of the two sets.
290 *
291 * @param c collection containing elements to be removed from this set
292 * @return <tt>true</tt> if this set changed as a result of the call
293 * @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 removeAll(Collection<?> c) {
301 return al.removeAll(c);
302 }
303
304 /**
305 * Retains only the elements in this set that are contained in the
306 * specified collection. In other words, removes from this set all of
307 * its elements that are not contained in the specified collection. If
308 * the specified collection is also a set, this operation effectively
309 * modifies this set so that its value is the <i>intersection</i> of the
310 * two sets.
311 *
312 * @param c collection containing elements to be retained in this set
313 * @return <tt>true</tt> if this set changed as a result of the call
314 * @throws ClassCastException if the class of an element of this set
315 * is incompatible with the specified collection (optional)
316 * @throws NullPointerException if this set contains a null element and the
317 * specified collection does not permit null elements (optional),
318 * or if the specified collection is null
319 * @see #remove(Object)
320 */
321 public boolean retainAll(Collection<?> c) {
322 return al.retainAll(c);
323 }
324
325 /**
326 * Returns an iterator over the elements contained in this set
327 * in the order in which these elements were added.
328 *
329 * <p>The returned iterator provides a snapshot of the state of the set
330 * when the iterator was constructed. No synchronization is needed while
331 * traversing the iterator. The iterator does <em>NOT</em> support the
332 * <tt>remove</tt> method.
333 *
334 * @return an iterator over the elements in this set
335 */
336 public Iterator<E> iterator() {
337 return al.iterator();
338 }
339
340 /**
341 * Compares the specified object with this set for equality.
342 * Returns {@code true} if the specified object is the same object
343 * as this object, or if it is also a {@link Set} and the elements
344 * returned by an {@linkplain List#iterator() iterator} over the
345 * specified set are the same as the elements returned by an
346 * iterator over this set. More formally, the two iterators are
347 * considered to return the same elements if they return the same
348 * number of elements and for every element {@code e1} returned by
349 * the iterator over the specified set, there is an element
350 * {@code e2} returned by the iterator over this set such that
351 * {@code (e1==null ? e2==null : e1.equals(e2))}.
352 *
353 * @param o object to be compared for equality with this set
354 * @return {@code true} if the specified object is equal to this set
355 */
356 public boolean equals(Object o) {
357 if (o == this )
358 return true;
359 if (!(o instanceof Set))
360 return false;
361 Set<?> set = (Set<?>) (o);
362 Iterator<?> it = set.iterator();
363
364 // Uses O(n^2) algorithm that is only appropriate
365 // for small sets, which CopyOnWriteArraySets should be.
366
367 // Use a single snapshot of underlying array
368 Object[] elements = al.getArray();
369 int len = elements.length;
370 // Mark matched elements to avoid re-checking
371 boolean[] matched = new boolean[len];
372 int k = 0;
373 outer: while (it.hasNext()) {
374 if (++k > len)
375 return false;
376 Object x = it.next();
377 for (int i = 0; i < len; ++i) {
378 if (!matched[i] && eq(x, elements[i])) {
379 matched[i] = true;
380 continue outer;
381 }
382 }
383 return false;
384 }
385 return k == len;
386 }
387
388 /**
389 * Test for equality, coping with nulls.
390 */
391 private static boolean eq(Object o1, Object o2) {
392 return (o1 == null ? o2 == null : o1.equals(o2));
393 }
394 }
|