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.Spliterator; |
14 |
import java.util.Spliterators; |
15 |
import java.util.function.Predicate; |
16 |
import java.util.function.Consumer; |
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<>(); |
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 set |
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 |
if (c.getClass() == CopyOnWriteArraySet.class) { |
90 |
@SuppressWarnings("unchecked") CopyOnWriteArraySet<E> cc = |
91 |
(CopyOnWriteArraySet<E>)c; |
92 |
al = new CopyOnWriteArrayList<E>(cc.al); |
93 |
} |
94 |
else { |
95 |
al = new CopyOnWriteArrayList<E>(); |
96 |
al.addAllAbsent(c); |
97 |
} |
98 |
} |
99 |
|
100 |
/** |
101 |
* Returns the number of elements in this set. |
102 |
* |
103 |
* @return the number of elements in this set |
104 |
*/ |
105 |
public int size() { |
106 |
return al.size(); |
107 |
} |
108 |
|
109 |
/** |
110 |
* Returns {@code true} if this set contains no elements. |
111 |
* |
112 |
* @return {@code true} if this set contains no elements |
113 |
*/ |
114 |
public boolean isEmpty() { |
115 |
return al.isEmpty(); |
116 |
} |
117 |
|
118 |
/** |
119 |
* Returns {@code true} if this set contains the specified element. |
120 |
* More formally, returns {@code true} if and only if this set |
121 |
* contains an element {@code e} such that {@code Objects.equals(o, e)}. |
122 |
* |
123 |
* @param o element whose presence in this set is to be tested |
124 |
* @return {@code true} if this set contains the specified element |
125 |
*/ |
126 |
public boolean contains(Object o) { |
127 |
return al.contains(o); |
128 |
} |
129 |
|
130 |
/** |
131 |
* Returns an array containing all of the elements in this set. |
132 |
* If this set makes any guarantees as to what order its elements |
133 |
* are returned by its iterator, this method must return the |
134 |
* elements in the same order. |
135 |
* |
136 |
* <p>The returned array will be "safe" in that no references to it |
137 |
* are maintained by this set. (In other words, this method must |
138 |
* allocate a new array even if this set is backed by an array). |
139 |
* The caller is thus free to modify the returned array. |
140 |
* |
141 |
* <p>This method acts as bridge between array-based and collection-based |
142 |
* APIs. |
143 |
* |
144 |
* @return an array containing all the elements in this set |
145 |
*/ |
146 |
public Object[] toArray() { |
147 |
return al.toArray(); |
148 |
} |
149 |
|
150 |
/** |
151 |
* Returns an array containing all of the elements in this set; the |
152 |
* runtime type of the returned array is that of the specified array. |
153 |
* If the set fits in the specified array, it is returned therein. |
154 |
* Otherwise, a new array is allocated with the runtime type of the |
155 |
* specified array and the size of this set. |
156 |
* |
157 |
* <p>If this set fits in the specified array with room to spare |
158 |
* (i.e., the array has more elements than this set), the element in |
159 |
* the array immediately following the end of the set is set to |
160 |
* {@code null}. (This is useful in determining the length of this |
161 |
* set <i>only</i> if the caller knows that this set does not contain |
162 |
* any null elements.) |
163 |
* |
164 |
* <p>If this set makes any guarantees as to what order its elements |
165 |
* are returned by its iterator, this method must return the elements |
166 |
* in the same order. |
167 |
* |
168 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
169 |
* array-based and collection-based APIs. Further, this method allows |
170 |
* precise control over the runtime type of the output array, and may, |
171 |
* under certain circumstances, be used to save allocation costs. |
172 |
* |
173 |
* <p>Suppose {@code x} is a set known to contain only strings. |
174 |
* The following code can be used to dump the set into a newly allocated |
175 |
* array of {@code String}: |
176 |
* |
177 |
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre> |
178 |
* |
179 |
* Note that {@code toArray(new Object[0])} is identical in function to |
180 |
* {@code toArray()}. |
181 |
* |
182 |
* @param a the array into which the elements of this set are to be |
183 |
* stored, if it is big enough; otherwise, a new array of the same |
184 |
* runtime type is allocated for this purpose. |
185 |
* @return an array containing all the elements in this set |
186 |
* @throws ArrayStoreException if the runtime type of the specified array |
187 |
* is not a supertype of the runtime type of every element in this |
188 |
* set |
189 |
* @throws NullPointerException if the specified array is null |
190 |
*/ |
191 |
public <T> T[] toArray(T[] a) { |
192 |
return al.toArray(a); |
193 |
} |
194 |
|
195 |
/** |
196 |
* Removes all of the elements from this set. |
197 |
* The set will be empty after this call returns. |
198 |
*/ |
199 |
public void clear() { |
200 |
al.clear(); |
201 |
} |
202 |
|
203 |
/** |
204 |
* Removes the specified element from this set if it is present. |
205 |
* More formally, removes an element {@code e} such that |
206 |
* {@code Objects.equals(o, e)}, if this set contains such an element. |
207 |
* Returns {@code true} if this set contained the element (or |
208 |
* equivalently, if this set changed as a result of the call). |
209 |
* (This set will not contain the element once the call returns.) |
210 |
* |
211 |
* @param o object to be removed from this set, if present |
212 |
* @return {@code true} if this set contained the specified element |
213 |
*/ |
214 |
public boolean remove(Object o) { |
215 |
return al.remove(o); |
216 |
} |
217 |
|
218 |
/** |
219 |
* Adds the specified element to this set if it is not already present. |
220 |
* More formally, adds the specified element {@code e} to this set if |
221 |
* the set contains no element {@code e2} such that |
222 |
* {@code Objects.equals(e, e2)}. |
223 |
* If this set already contains the element, the call leaves the set |
224 |
* unchanged and returns {@code false}. |
225 |
* |
226 |
* @param e element to be added to this set |
227 |
* @return {@code true} if this set did not already contain the specified |
228 |
* element |
229 |
*/ |
230 |
public boolean add(E e) { |
231 |
return al.addIfAbsent(e); |
232 |
} |
233 |
|
234 |
/** |
235 |
* Returns {@code true} if this set contains all of the elements of the |
236 |
* specified collection. If the specified collection is also a set, this |
237 |
* method returns {@code true} if it is a <i>subset</i> of this set. |
238 |
* |
239 |
* @param c collection to be checked for containment in this set |
240 |
* @return {@code true} if this set contains all of the elements of the |
241 |
* specified collection |
242 |
* @throws NullPointerException if the specified collection is null |
243 |
* @see #contains(Object) |
244 |
*/ |
245 |
public boolean containsAll(Collection<?> c) { |
246 |
return al.containsAll(c); |
247 |
} |
248 |
|
249 |
/** |
250 |
* Adds all of the elements in the specified collection to this set if |
251 |
* they're not already present. If the specified collection is also a |
252 |
* set, the {@code addAll} operation effectively modifies this set so |
253 |
* that its value is the <i>union</i> of the two sets. The behavior of |
254 |
* this operation is undefined if the specified collection is modified |
255 |
* while the operation is in progress. |
256 |
* |
257 |
* @param c collection containing elements to be added to this set |
258 |
* @return {@code true} if this set changed as a result of the call |
259 |
* @throws NullPointerException if the specified collection is null |
260 |
* @see #add(Object) |
261 |
*/ |
262 |
public boolean addAll(Collection<? extends E> c) { |
263 |
return al.addAllAbsent(c) > 0; |
264 |
} |
265 |
|
266 |
/** |
267 |
* Removes from this set all of its elements that are contained in the |
268 |
* specified collection. If the specified collection is also a set, |
269 |
* this operation effectively modifies this set so that its value is the |
270 |
* <i>asymmetric set difference</i> of the two sets. |
271 |
* |
272 |
* @param c collection containing elements to be removed from this set |
273 |
* @return {@code true} if this set changed as a result of the call |
274 |
* @throws ClassCastException if the class of an element of this set |
275 |
* is incompatible with the specified collection (optional) |
276 |
* @throws NullPointerException if this set contains a null element and the |
277 |
* specified collection does not permit null elements (optional), |
278 |
* or if the specified collection is null |
279 |
* @see #remove(Object) |
280 |
*/ |
281 |
public boolean removeAll(Collection<?> c) { |
282 |
return al.removeAll(c); |
283 |
} |
284 |
|
285 |
/** |
286 |
* Retains only the elements in this set that are contained in the |
287 |
* specified collection. In other words, removes from this set all of |
288 |
* its elements that are not contained in the specified collection. If |
289 |
* the specified collection is also a set, this operation effectively |
290 |
* modifies this set so that its value is the <i>intersection</i> of the |
291 |
* two sets. |
292 |
* |
293 |
* @param c collection containing elements to be retained in this set |
294 |
* @return {@code true} if this set changed as a result of the call |
295 |
* @throws ClassCastException if the class of an element of this set |
296 |
* is incompatible with the specified collection (optional) |
297 |
* @throws NullPointerException if this set contains a null element and the |
298 |
* specified collection does not permit null elements (optional), |
299 |
* or if the specified collection is null |
300 |
* @see #remove(Object) |
301 |
*/ |
302 |
public boolean retainAll(Collection<?> c) { |
303 |
return al.retainAll(c); |
304 |
} |
305 |
|
306 |
/** |
307 |
* Returns an iterator over the elements contained in this set |
308 |
* in the order in which these elements were added. |
309 |
* |
310 |
* <p>The returned iterator provides a snapshot of the state of the set |
311 |
* when the iterator was constructed. No synchronization is needed while |
312 |
* traversing the iterator. The iterator does <em>NOT</em> support the |
313 |
* {@code remove} method. |
314 |
* |
315 |
* @return an iterator over the elements in this set |
316 |
*/ |
317 |
public Iterator<E> iterator() { |
318 |
return al.iterator(); |
319 |
} |
320 |
|
321 |
/** |
322 |
* Compares the specified object with this set for equality. |
323 |
* Returns {@code true} if the specified object is the same object |
324 |
* as this object, or if it is also a {@link Set} and the elements |
325 |
* returned by an {@linkplain Set#iterator() iterator} over the |
326 |
* specified set are the same as the elements returned by an |
327 |
* iterator over this set. More formally, the two iterators are |
328 |
* considered to return the same elements if they return the same |
329 |
* number of elements and for every element {@code e1} returned by |
330 |
* the iterator over the specified set, there is an element |
331 |
* {@code e2} returned by the iterator over this set such that |
332 |
* {@code Objects.equals(e1, e2)}. |
333 |
* |
334 |
* @param o object to be compared for equality with this set |
335 |
* @return {@code true} if the specified object is equal to this set |
336 |
*/ |
337 |
public boolean equals(Object o) { |
338 |
if (o == this) |
339 |
return true; |
340 |
if (!(o instanceof Set)) |
341 |
return false; |
342 |
Set<?> set = (Set<?>)(o); |
343 |
Iterator<?> it = set.iterator(); |
344 |
|
345 |
// Uses O(n^2) algorithm that is only appropriate |
346 |
// for small sets, which CopyOnWriteArraySets should be. |
347 |
|
348 |
// Use a single snapshot of underlying array |
349 |
Object[] elements = al.getArray(); |
350 |
int len = elements.length; |
351 |
// Mark matched elements to avoid re-checking |
352 |
boolean[] matched = new boolean[len]; |
353 |
int k = 0; |
354 |
outer: while (it.hasNext()) { |
355 |
if (++k > len) |
356 |
return false; |
357 |
Object x = it.next(); |
358 |
for (int i = 0; i < len; ++i) { |
359 |
if (!matched[i] && eq(x, elements[i])) { |
360 |
matched[i] = true; |
361 |
continue outer; |
362 |
} |
363 |
} |
364 |
return false; |
365 |
} |
366 |
return k == len; |
367 |
} |
368 |
|
369 |
public boolean removeIf(Predicate<? super E> filter) { |
370 |
return al.removeIf(filter); |
371 |
} |
372 |
|
373 |
public void forEach(Consumer<? super E> action) { |
374 |
al.forEach(action); |
375 |
} |
376 |
|
377 |
/** |
378 |
* Returns a {@link Spliterator} over the elements in this set in the order |
379 |
* in which these elements were added. |
380 |
* |
381 |
* <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE}, |
382 |
* {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and |
383 |
* {@link Spliterator#SUBSIZED}. |
384 |
* |
385 |
* <p>The spliterator provides a snapshot of the state of the set |
386 |
* when the spliterator was constructed. No synchronization is needed while |
387 |
* operating on the spliterator. The spliterator does <em>NOT</em> support |
388 |
* the {@code remove}, {@code set} or {@code add} methods. |
389 |
* |
390 |
* @return a {@code Spliterator} over the elements in this set |
391 |
* @since 1.8 |
392 |
*/ |
393 |
public Spliterator<E> spliterator() { |
394 |
return Spliterators.spliterator |
395 |
(al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT); |
396 |
} |
397 |
|
398 |
/** |
399 |
* Tests for equality, coping with nulls. |
400 |
*/ |
401 |
private static boolean eq(Object o1, Object o2) { |
402 |
return (o1 == null) ? o2 == null : o1.equals(o2); |
403 |
} |
404 |
} |