1/*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation.  Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25/*
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
29 * file:
30 *
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
34 */
35
36package java.util.concurrent;
37
38import java.util.AbstractSet;
39import java.util.Collection;
40import java.util.Iterator;
41import java.util.Objects;
42import java.util.Set;
43import java.util.Spliterator;
44import java.util.Spliterators;
45import java.util.function.Consumer;
46import java.util.function.Predicate;
47
48// BEGIN android-note
49// removed link to collections framework docs
50// fixed framework docs link to "Collection#optional"
51// END android-note
52
53/**
54 * A {@link java.util.Set} that uses an internal {@link CopyOnWriteArrayList}
55 * for all of its operations.  Thus, it shares the same basic properties:
56 * <ul>
57 *  <li>It is best suited for applications in which set sizes generally
58 *       stay small, read-only operations
59 *       vastly outnumber mutative operations, and you need
60 *       to prevent interference among threads during traversal.
61 *  <li>It is thread-safe.
62 *  <li>Mutative operations ({@code add}, {@code set}, {@code remove}, etc.)
63 *      are expensive since they usually entail copying the entire underlying
64 *      array.
65 *  <li>Iterators do not support the mutative {@code remove} operation.
66 *  <li>Traversal via iterators is fast and cannot encounter
67 *      interference from other threads. Iterators rely on
68 *      unchanging snapshots of the array at the time the iterators were
69 *      constructed.
70 * </ul>
71 *
72 * <p><b>Sample Usage.</b> The following code sketch uses a
73 * copy-on-write set to maintain a set of Handler objects that
74 * perform some action upon state updates.
75 *
76 * <pre> {@code
77 * class Handler { void handle(); ... }
78 *
79 * class X {
80 *   private final CopyOnWriteArraySet<Handler> handlers
81 *     = new CopyOnWriteArraySet<>();
82 *   public void addHandler(Handler h) { handlers.add(h); }
83 *
84 *   private long internalState;
85 *   private synchronized void changeState() { internalState = ...; }
86 *
87 *   public void update() {
88 *     changeState();
89 *     for (Handler handler : handlers)
90 *       handler.handle();
91 *   }
92 * }}</pre>
93 *
94 * @see CopyOnWriteArrayList
95 * @since 1.5
96 * @author Doug Lea
97 * @param <E> the type of elements held in this set
98 */
99public class CopyOnWriteArraySet<E> extends AbstractSet<E>
100        implements java.io.Serializable {
101    private static final long serialVersionUID = 5457747651344034263L;
102
103    private final CopyOnWriteArrayList<E> al;
104
105    /**
106     * Creates an empty set.
107     */
108    public CopyOnWriteArraySet() {
109        al = new CopyOnWriteArrayList<E>();
110    }
111
112    /**
113     * Creates a set containing all of the elements of the specified
114     * collection.
115     *
116     * @param c the collection of elements to initially contain
117     * @throws NullPointerException if the specified collection is null
118     */
119    public CopyOnWriteArraySet(Collection<? extends E> c) {
120        if (c.getClass() == CopyOnWriteArraySet.class) {
121            @SuppressWarnings("unchecked") CopyOnWriteArraySet<E> cc =
122                (CopyOnWriteArraySet<E>)c;
123            al = new CopyOnWriteArrayList<E>(cc.al);
124        }
125        else {
126            al = new CopyOnWriteArrayList<E>();
127            al.addAllAbsent(c);
128        }
129    }
130
131    /**
132     * Returns the number of elements in this set.
133     *
134     * @return the number of elements in this set
135     */
136    public int size() {
137        return al.size();
138    }
139
140    /**
141     * Returns {@code true} if this set contains no elements.
142     *
143     * @return {@code true} if this set contains no elements
144     */
145    public boolean isEmpty() {
146        return al.isEmpty();
147    }
148
149    /**
150     * Returns {@code true} if this set contains the specified element.
151     * More formally, returns {@code true} if and only if this set
152     * contains an element {@code e} such that {@code Objects.equals(o, e)}.
153     *
154     * @param o element whose presence in this set is to be tested
155     * @return {@code true} if this set contains the specified element
156     */
157    public boolean contains(Object o) {
158        return al.contains(o);
159    }
160
161    /**
162     * Returns an array containing all of the elements in this set.
163     * If this set makes any guarantees as to what order its elements
164     * are returned by its iterator, this method must return the
165     * elements in the same order.
166     *
167     * <p>The returned array will be "safe" in that no references to it
168     * are maintained by this set.  (In other words, this method must
169     * allocate a new array even if this set is backed by an array).
170     * The caller is thus free to modify the returned array.
171     *
172     * <p>This method acts as bridge between array-based and collection-based
173     * APIs.
174     *
175     * @return an array containing all the elements in this set
176     */
177    public Object[] toArray() {
178        return al.toArray();
179    }
180
181    /**
182     * Returns an array containing all of the elements in this set; the
183     * runtime type of the returned array is that of the specified array.
184     * If the set fits in the specified array, it is returned therein.
185     * Otherwise, a new array is allocated with the runtime type of the
186     * specified array and the size of this set.
187     *
188     * <p>If this set fits in the specified array with room to spare
189     * (i.e., the array has more elements than this set), the element in
190     * the array immediately following the end of the set is set to
191     * {@code null}.  (This is useful in determining the length of this
192     * set <i>only</i> if the caller knows that this set does not contain
193     * any null elements.)
194     *
195     * <p>If this set makes any guarantees as to what order its elements
196     * are returned by its iterator, this method must return the elements
197     * in the same order.
198     *
199     * <p>Like the {@link #toArray()} method, this method acts as bridge between
200     * array-based and collection-based APIs.  Further, this method allows
201     * precise control over the runtime type of the output array, and may,
202     * under certain circumstances, be used to save allocation costs.
203     *
204     * <p>Suppose {@code x} is a set known to contain only strings.
205     * The following code can be used to dump the set into a newly allocated
206     * array of {@code String}:
207     *
208     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
209     *
210     * Note that {@code toArray(new Object[0])} is identical in function to
211     * {@code toArray()}.
212     *
213     * @param a the array into which the elements of this set are to be
214     *        stored, if it is big enough; otherwise, a new array of the same
215     *        runtime type is allocated for this purpose.
216     * @return an array containing all the elements in this set
217     * @throws ArrayStoreException if the runtime type of the specified array
218     *         is not a supertype of the runtime type of every element in this
219     *         set
220     * @throws NullPointerException if the specified array is null
221     */
222    public <T> T[] toArray(T[] a) {
223        return al.toArray(a);
224    }
225
226    /**
227     * Removes all of the elements from this set.
228     * The set will be empty after this call returns.
229     */
230    public void clear() {
231        al.clear();
232    }
233
234    /**
235     * Removes the specified element from this set if it is present.
236     * More formally, removes an element {@code e} such that
237     * {@code Objects.equals(o, e)}, if this set contains such an element.
238     * Returns {@code true} if this set contained the element (or
239     * equivalently, if this set changed as a result of the call).
240     * (This set will not contain the element once the call returns.)
241     *
242     * @param o object to be removed from this set, if present
243     * @return {@code true} if this set contained the specified element
244     */
245    public boolean remove(Object o) {
246        return al.remove(o);
247    }
248
249    /**
250     * Adds the specified element to this set if it is not already present.
251     * More formally, adds the specified element {@code e} to this set if
252     * the set contains no element {@code e2} such that
253     * {@code Objects.equals(e, e2)}.
254     * If this set already contains the element, the call leaves the set
255     * unchanged and returns {@code false}.
256     *
257     * @param e element to be added to this set
258     * @return {@code true} if this set did not already contain the specified
259     *         element
260     */
261    public boolean add(E e) {
262        return al.addIfAbsent(e);
263    }
264
265    /**
266     * Returns {@code true} if this set contains all of the elements of the
267     * specified collection.  If the specified collection is also a set, this
268     * method returns {@code true} if it is a <i>subset</i> of this set.
269     *
270     * @param  c collection to be checked for containment in this set
271     * @return {@code true} if this set contains all of the elements of the
272     *         specified collection
273     * @throws NullPointerException if the specified collection is null
274     * @see #contains(Object)
275     */
276    public boolean containsAll(Collection<?> c) {
277        return (c instanceof Set)
278            ? compareSets(al.getArray(), (Set<?>) c) >= 0
279            : al.containsAll(c);
280    }
281
282    /**
283     * Tells whether the objects in snapshot (regarded as a set) are a
284     * superset of the given set.
285     *
286     * @return -1 if snapshot is not a superset, 0 if the two sets
287     * contain precisely the same elements, and 1 if snapshot is a
288     * proper superset of the given set
289     */
290    private static int compareSets(Object[] snapshot, Set<?> set) {
291        // Uses O(n^2) algorithm, that is only appropriate for small
292        // sets, which CopyOnWriteArraySets should be.
293        //
294        // Optimize up to O(n) if the two sets share a long common prefix,
295        // as might happen if one set was created as a copy of the other set.
296
297        final int len = snapshot.length;
298        // Mark matched elements to avoid re-checking
299        final boolean[] matched = new boolean[len];
300
301        // j is the largest int with matched[i] true for { i | 0 <= i < j }
302        int j = 0;
303        outer: for (Object x : set) {
304            for (int i = j; i < len; i++) {
305                if (!matched[i] && Objects.equals(x, snapshot[i])) {
306                    matched[i] = true;
307                    if (i == j)
308                        do { j++; } while (j < len && matched[j]);
309                    continue outer;
310                }
311            }
312            return -1;
313        }
314        return (j == len) ? 0 : 1;
315    }
316
317    /**
318     * Adds all of the elements in the specified collection to this set if
319     * they're not already present.  If the specified collection is also a
320     * set, the {@code addAll} operation effectively modifies this set so
321     * that its value is the <i>union</i> of the two sets.  The behavior of
322     * this operation is undefined if the specified collection is modified
323     * while the operation is in progress.
324     *
325     * @param  c collection containing elements to be added to this set
326     * @return {@code true} if this set changed as a result of the call
327     * @throws NullPointerException if the specified collection is null
328     * @see #add(Object)
329     */
330    public boolean addAll(Collection<? extends E> c) {
331        return al.addAllAbsent(c) > 0;
332    }
333
334    /**
335     * Removes from this set all of its elements that are contained in the
336     * specified collection.  If the specified collection is also a set,
337     * this operation effectively modifies this set so that its value is the
338     * <i>asymmetric set difference</i> of the two sets.
339     *
340     * @param  c collection containing elements to be removed from this set
341     * @return {@code true} if this set changed as a result of the call
342     * @throws ClassCastException if the class of an element of this set
343     *         is incompatible with the specified collection
344     * (<a href="../Collection.html#optional-restrictions">optional</a>)
345     * @throws NullPointerException if this set contains a null element and the
346     *         specified collection does not permit null elements
347     * (<a href="../Collection.html#optional-restrictions">optional</a>),
348     *         or if the specified collection is null
349     * @see #remove(Object)
350     */
351    public boolean removeAll(Collection<?> c) {
352        return al.removeAll(c);
353    }
354
355    /**
356     * Retains only the elements in this set that are contained in the
357     * specified collection.  In other words, removes from this set all of
358     * its elements that are not contained in the specified collection.  If
359     * the specified collection is also a set, this operation effectively
360     * modifies this set so that its value is the <i>intersection</i> of the
361     * two sets.
362     *
363     * @param  c collection containing elements to be retained in this set
364     * @return {@code true} if this set changed as a result of the call
365     * @throws ClassCastException if the class of an element of this set
366     *         is incompatible with the specified collection
367     * (<a href="../Collection.html#optional-restrictions">optional</a>)
368     * @throws NullPointerException if this set contains a null element and the
369     *         specified collection does not permit null elements
370     * (<a href="../Collection.html#optional-restrictions">optional</a>),
371     *         or if the specified collection is null
372     * @see #remove(Object)
373     */
374    public boolean retainAll(Collection<?> c) {
375        return al.retainAll(c);
376    }
377
378    /**
379     * Returns an iterator over the elements contained in this set
380     * in the order in which these elements were added.
381     *
382     * <p>The returned iterator provides a snapshot of the state of the set
383     * when the iterator was constructed. No synchronization is needed while
384     * traversing the iterator. The iterator does <em>NOT</em> support the
385     * {@code remove} method.
386     *
387     * @return an iterator over the elements in this set
388     */
389    public Iterator<E> iterator() {
390        return al.iterator();
391    }
392
393    /**
394     * Compares the specified object with this set for equality.
395     * Returns {@code true} if the specified object is the same object
396     * as this object, or if it is also a {@link Set} and the elements
397     * returned by an {@linkplain Set#iterator() iterator} over the
398     * specified set are the same as the elements returned by an
399     * iterator over this set.  More formally, the two iterators are
400     * considered to return the same elements if they return the same
401     * number of elements and for every element {@code e1} returned by
402     * the iterator over the specified set, there is an element
403     * {@code e2} returned by the iterator over this set such that
404     * {@code Objects.equals(e1, e2)}.
405     *
406     * @param o object to be compared for equality with this set
407     * @return {@code true} if the specified object is equal to this set
408     */
409    public boolean equals(Object o) {
410        return (o == this)
411            || ((o instanceof Set)
412                && compareSets(al.getArray(), (Set<?>) o) == 0);
413    }
414
415    public boolean removeIf(Predicate<? super E> filter) {
416        return al.removeIf(filter);
417    }
418
419    public void forEach(Consumer<? super E> action) {
420        al.forEach(action);
421    }
422
423    /**
424     * Returns a {@link Spliterator} over the elements in this set in the order
425     * in which these elements were added.
426     *
427     * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
428     * {@link Spliterator#DISTINCT}, {@link Spliterator#SIZED}, and
429     * {@link Spliterator#SUBSIZED}.
430     *
431     * <p>The spliterator provides a snapshot of the state of the set
432     * when the spliterator was constructed. No synchronization is needed while
433     * operating on the spliterator.
434     *
435     * @return a {@code Spliterator} over the elements in this set
436     * @since 1.8
437     */
438    public Spliterator<E> spliterator() {
439        return Spliterators.spliterator
440            (al.getArray(), Spliterator.IMMUTABLE | Spliterator.DISTINCT);
441    }
442}
443