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