17 |
|
* vastly outnumber mutative operations, and you need |
18 |
|
* to prevent interference among threads during traversal. |
19 |
|
* <li>It is thread-safe. |
20 |
< |
* <li>Mutative operations(add, set, remove, etc) are expensive |
20 |
> |
* <li>Mutative operations (add, set, remove, etc) are expensive |
21 |
|
* since they usually entail copying the entire underlying array. |
22 |
< |
* <li>Iterators do not support the mutative remove operation |
23 |
< |
* <li>Traversal via iterators is very fast and cannot ever encounter |
22 |
> |
* <li>Iterators do not support the mutative remove operation. |
23 |
> |
* <li>Traversal via iterators is fast and cannot encounter |
24 |
|
* interference from other threads. Iterators rely on |
25 |
|
* unchanging snapshots of the array at the time the iterators were |
26 |
|
* constructed. |
27 |
|
* </ul> |
28 |
< |
* <p> |
29 |
< |
* <b>Sample Usage.</b> Probably the main application |
30 |
< |
* of copy-on-write sets are classes that maintain |
31 |
< |
* sets of Handler objects |
32 |
< |
* that must be multicasted to upon an update command. This |
33 |
< |
* is a classic case where you do not want to be holding a |
34 |
< |
* lock while sending a message, and where traversals normally |
35 |
< |
* vastly overwhelm additions. |
28 |
> |
* |
29 |
> |
* <p> <b>Sample Usage.</b> The following code sketch uses a |
30 |
> |
* copy-on-write set to maintain a set of Handler objects that |
31 |
> |
* perform some action upon state updates. |
32 |
> |
* |
33 |
|
* <pre> |
34 |
|
* class Handler { void handle(); ... } |
35 |
|
* |
42 |
|
* |
43 |
|
* public void update() { |
44 |
|
* changeState(); |
45 |
< |
* Iterator<Handler> it = handlers.iterator(); |
49 |
< |
* while (it.hasNext()) |
45 |
> |
* for (Handler handler : handlers) |
46 |
|
* it.next().handle(); |
47 |
|
* } |
48 |
|
* } |
58 |
|
* @param <E> the type of elements held in this collection |
59 |
|
*/ |
60 |
|
public class CopyOnWriteArraySet<E> extends AbstractSet<E> |
61 |
< |
implements Cloneable, java.io.Serializable { |
61 |
> |
implements java.io.Serializable { |
62 |
|
private static final long serialVersionUID = 5457747651344034263L; |
63 |
|
|
64 |
|
private final CopyOnWriteArrayList<E> al; |
95 |
|
public boolean removeAll(Collection<?> c) { return al.removeAll(c); } |
96 |
|
public boolean retainAll(Collection<?> c) { return al.retainAll(c); } |
97 |
|
|
102 |
– |
public Object clone() { return new CopyOnWriteArraySet(al); } |
98 |
|
} |