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