ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.129
Committed: Tue May 19 06:32:59 2015 UTC (9 years ago) by jsr166
Branch: MAIN
Changes since 1.128: +7 -12 lines
Log Message:
replace eq with (standard) Objects.equals

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.17 * Expert Group. Adapted and released, under explicit permission,
4 dl 1.15 * from JDK ArrayList.java which carries the following copyright:
5 dl 1.3 *
6     * Copyright 1997 by Sun Microsystems, Inc.,
7     * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
8     * All rights reserved.
9     *
10     * This software is the confidential and proprietary information
11     * of Sun Microsystems, Inc. ("Confidential Information"). You
12     * shall not disclose such Confidential Information and shall use
13     * it only in accordance with the terms of the license agreement
14     * you entered into with Sun.
15 dl 1.2 */
16    
17 tim 1.1 package java.util.concurrent;
18 jsr166 1.119
19 dl 1.98 import java.util.AbstractList;
20 dl 1.93 import java.util.Arrays;
21     import java.util.Collection;
22 dl 1.106 import java.util.Comparator;
23 dl 1.98 import java.util.ConcurrentModificationException;
24     import java.util.Iterator;
25 dl 1.93 import java.util.List;
26     import java.util.ListIterator;
27 dl 1.98 import java.util.NoSuchElementException;
28 jsr166 1.129 import java.util.Objects;
29 dl 1.93 import java.util.RandomAccess;
30     import java.util.Spliterator;
31 dl 1.99 import java.util.Spliterators;
32 dl 1.98 import java.util.function.Consumer;
33 dl 1.106 import java.util.function.Predicate;
34     import java.util.function.UnaryOperator;
35 tim 1.1
36     /**
37 dl 1.28 * A thread-safe variant of {@link java.util.ArrayList} in which all mutative
38 jsr166 1.92 * operations ({@code add}, {@code set}, and so on) are implemented by
39 jsr166 1.35 * making a fresh copy of the underlying array.
40 tim 1.1 *
41 jsr166 1.91 * <p>This is ordinarily too costly, but may be <em>more</em> efficient
42 dl 1.12 * than alternatives when traversal operations vastly outnumber
43     * mutations, and is useful when you cannot or don't want to
44     * synchronize traversals, yet need to preclude interference among
45 dl 1.15 * concurrent threads. The "snapshot" style iterator method uses a
46     * reference to the state of the array at the point that the iterator
47     * was created. This array never changes during the lifetime of the
48     * iterator, so interference is impossible and the iterator is
49 jsr166 1.92 * guaranteed not to throw {@code ConcurrentModificationException}.
50 dl 1.15 * The iterator will not reflect additions, removals, or changes to
51     * the list since the iterator was created. Element-changing
52 jsr166 1.92 * operations on iterators themselves ({@code remove}, {@code set}, and
53     * {@code add}) are not supported. These methods throw
54     * {@code UnsupportedOperationException}.
55 dl 1.24 *
56 jsr166 1.92 * <p>All elements are permitted, including {@code null}.
57 jsr166 1.35 *
58 jsr166 1.56 * <p>Memory consistency effects: As with other concurrent
59     * collections, actions in a thread prior to placing an object into a
60     * {@code CopyOnWriteArrayList}
61     * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
62     * actions subsequent to the access or removal of that element from
63     * the {@code CopyOnWriteArrayList} in another thread.
64     *
65 dl 1.24 * <p>This class is a member of the
66 jsr166 1.64 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
67 dl 1.24 * Java Collections Framework</a>.
68     *
69 dl 1.6 * @since 1.5
70     * @author Doug Lea
71 jsr166 1.118 * @param <E> the type of elements held in this list
72 dl 1.6 */
73 tim 1.1 public class CopyOnWriteArrayList<E>
74 dl 1.40 implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
75 dl 1.11 private static final long serialVersionUID = 8673264195747942595L;
76 tim 1.1
77 jsr166 1.124 /**
78     * The lock protecting all mutators. (We have a mild preference
79     * for builtin monitors over ReentrantLock when either will do.)
80     */
81     final transient Object lock = new Object();
82 dl 1.42
83 dl 1.40 /** The array, accessed only via getArray/setArray. */
84 jsr166 1.95 private transient volatile Object[] array;
85 tim 1.1
86 dl 1.57 /**
87 jsr166 1.60 * Gets the array. Non-private so as to also be accessible
88     * from CopyOnWriteArraySet class.
89 dl 1.57 */
90 jsr166 1.63 final Object[] getArray() {
91 jsr166 1.59 return array;
92 dl 1.57 }
93    
94     /**
95 jsr166 1.60 * Sets the array.
96 dl 1.57 */
97 jsr166 1.59 final void setArray(Object[] a) {
98     array = a;
99 dl 1.57 }
100 tim 1.1
101     /**
102 dl 1.15 * Creates an empty list.
103 tim 1.1 */
104     public CopyOnWriteArrayList() {
105 dl 1.41 setArray(new Object[0]);
106 tim 1.1 }
107    
108     /**
109 dl 1.15 * Creates a list containing the elements of the specified
110 jsr166 1.32 * collection, in the order they are returned by the collection's
111 tim 1.1 * iterator.
112 jsr166 1.32 *
113 dl 1.6 * @param c the collection of initially held elements
114 jsr166 1.35 * @throws NullPointerException if the specified collection is null
115 tim 1.1 */
116 tim 1.22 public CopyOnWriteArrayList(Collection<? extends E> c) {
117 dl 1.106 Object[] elements;
118     if (c.getClass() == CopyOnWriteArrayList.class)
119     elements = ((CopyOnWriteArrayList<?>)c).getArray();
120     else {
121     elements = c.toArray();
122     // c.toArray might (incorrectly) not return Object[] (see 6260652)
123     if (elements.getClass() != Object[].class)
124     elements = Arrays.copyOf(elements, elements.length, Object[].class);
125     }
126 jsr166 1.67 setArray(elements);
127 tim 1.1 }
128    
129     /**
130 jsr166 1.35 * Creates a list holding a copy of the given array.
131 tim 1.9 *
132     * @param toCopyIn the array (a copy of this array is used as the
133     * internal array)
134 jsr166 1.38 * @throws NullPointerException if the specified array is null
135 jsr166 1.30 */
136 tim 1.1 public CopyOnWriteArrayList(E[] toCopyIn) {
137 jsr166 1.67 setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
138 tim 1.1 }
139    
140     /**
141 dl 1.15 * Returns the number of elements in this list.
142 tim 1.1 *
143 jsr166 1.35 * @return the number of elements in this list
144 tim 1.1 */
145     public int size() {
146 dl 1.40 return getArray().length;
147 tim 1.1 }
148    
149     /**
150 jsr166 1.92 * Returns {@code true} if this list contains no elements.
151 tim 1.1 *
152 jsr166 1.92 * @return {@code true} if this list contains no elements
153 tim 1.1 */
154     public boolean isEmpty() {
155     return size() == 0;
156     }
157    
158 dl 1.43 /**
159 dl 1.40 * static version of indexOf, to allow repeated calls without
160 dl 1.41 * needing to re-acquire array each time.
161 dl 1.40 * @param o element to search for
162     * @param elements the array
163     * @param index first index to search
164     * @param fence one past last index to search
165     * @return index of element, or -1 if absent
166     */
167 dl 1.41 private static int indexOf(Object o, Object[] elements,
168 dl 1.40 int index, int fence) {
169     if (o == null) {
170     for (int i = index; i < fence; i++)
171     if (elements[i] == null)
172     return i;
173     } else {
174     for (int i = index; i < fence; i++)
175     if (o.equals(elements[i]))
176     return i;
177     }
178     return -1;
179     }
180 dl 1.41
181     /**
182 dl 1.40 * static version of lastIndexOf.
183     * @param o element to search for
184     * @param elements the array
185     * @param index first index to search
186     * @return index of element, or -1 if absent
187     */
188     private static int lastIndexOf(Object o, Object[] elements, int index) {
189     if (o == null) {
190     for (int i = index; i >= 0; i--)
191     if (elements[i] == null)
192     return i;
193     } else {
194     for (int i = index; i >= 0; i--)
195     if (o.equals(elements[i]))
196     return i;
197     }
198     return -1;
199     }
200    
201 tim 1.1 /**
202 jsr166 1.92 * Returns {@code true} if this list contains the specified element.
203     * More formally, returns {@code true} if and only if this list contains
204 jsr166 1.116 * at least one element {@code e} such that {@code Objects.equals(o, e)}.
205 tim 1.1 *
206 jsr166 1.35 * @param o element whose presence in this list is to be tested
207 jsr166 1.92 * @return {@code true} if this list contains the specified element
208 tim 1.1 */
209 jsr166 1.35 public boolean contains(Object o) {
210 dl 1.41 Object[] elements = getArray();
211 dl 1.40 return indexOf(o, elements, 0, elements.length) >= 0;
212 tim 1.1 }
213    
214     /**
215 jsr166 1.35 * {@inheritDoc}
216 tim 1.1 */
217 jsr166 1.35 public int indexOf(Object o) {
218 dl 1.41 Object[] elements = getArray();
219 dl 1.40 return indexOf(o, elements, 0, elements.length);
220 tim 1.1 }
221    
222     /**
223 jsr166 1.35 * Returns the index of the first occurrence of the specified element in
224 jsr166 1.92 * this list, searching forwards from {@code index}, or returns -1 if
225 jsr166 1.35 * the element is not found.
226 jsr166 1.92 * More formally, returns the lowest index {@code i} such that
227 jsr166 1.35 * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>,
228     * or -1 if there is no such index.
229     *
230     * @param e element to search for
231     * @param index index to start searching from
232     * @return the index of the first occurrence of the element in
233 jsr166 1.92 * this list at position {@code index} or later in the list;
234     * {@code -1} if the element is not found.
235 jsr166 1.35 * @throws IndexOutOfBoundsException if the specified index is negative
236 tim 1.1 */
237 jsr166 1.35 public int indexOf(E e, int index) {
238 dl 1.41 Object[] elements = getArray();
239 jsr166 1.67 return indexOf(e, elements, index, elements.length);
240 tim 1.1 }
241    
242     /**
243 jsr166 1.35 * {@inheritDoc}
244 tim 1.1 */
245 jsr166 1.35 public int lastIndexOf(Object o) {
246 dl 1.41 Object[] elements = getArray();
247 dl 1.40 return lastIndexOf(o, elements, elements.length - 1);
248 tim 1.1 }
249    
250     /**
251 jsr166 1.35 * Returns the index of the last occurrence of the specified element in
252 jsr166 1.92 * this list, searching backwards from {@code index}, or returns -1 if
253 jsr166 1.35 * the element is not found.
254 jsr166 1.92 * More formally, returns the highest index {@code i} such that
255 jsr166 1.35 * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(e==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;e.equals(get(i))))</tt>,
256     * or -1 if there is no such index.
257     *
258     * @param e element to search for
259     * @param index index to start searching backwards from
260     * @return the index of the last occurrence of the element at position
261 jsr166 1.92 * less than or equal to {@code index} in this list;
262 jsr166 1.35 * -1 if the element is not found.
263     * @throws IndexOutOfBoundsException if the specified index is greater
264     * than or equal to the current size of this list
265 tim 1.1 */
266 jsr166 1.35 public int lastIndexOf(E e, int index) {
267 dl 1.41 Object[] elements = getArray();
268 jsr166 1.67 return lastIndexOf(e, elements, index);
269 tim 1.1 }
270    
271     /**
272     * Returns a shallow copy of this list. (The elements themselves
273     * are not copied.)
274     *
275 jsr166 1.35 * @return a clone of this list
276 tim 1.1 */
277     public Object clone() {
278     try {
279 jsr166 1.83 @SuppressWarnings("unchecked")
280     CopyOnWriteArrayList<E> clone =
281     (CopyOnWriteArrayList<E>) super.clone();
282     clone.resetLock();
283     return clone;
284 tim 1.1 } catch (CloneNotSupportedException e) {
285     // this shouldn't happen, since we are Cloneable
286     throw new InternalError();
287     }
288     }
289    
290     /**
291     * Returns an array containing all of the elements in this list
292 jsr166 1.35 * in proper sequence (from first to last element).
293     *
294     * <p>The returned array will be "safe" in that no references to it are
295     * maintained by this list. (In other words, this method must allocate
296     * a new array). The caller is thus free to modify the returned array.
297 jsr166 1.36 *
298 jsr166 1.35 * <p>This method acts as bridge between array-based and collection-based
299     * APIs.
300     *
301     * @return an array containing all the elements in this list
302 tim 1.1 */
303     public Object[] toArray() {
304 dl 1.40 Object[] elements = getArray();
305 jsr166 1.67 return Arrays.copyOf(elements, elements.length);
306 tim 1.1 }
307    
308     /**
309 jsr166 1.35 * Returns an array containing all of the elements in this list in
310     * proper sequence (from first to last element); the runtime type of
311     * the returned array is that of the specified array. If the list fits
312     * in the specified array, it is returned therein. Otherwise, a new
313     * array is allocated with the runtime type of the specified array and
314     * the size of this list.
315 jsr166 1.32 *
316     * <p>If this list fits in the specified array with room to spare
317 jsr166 1.35 * (i.e., the array has more elements than this list), the element in
318     * the array immediately following the end of the list is set to
319 jsr166 1.92 * {@code null}. (This is useful in determining the length of this
320 jsr166 1.35 * list <i>only</i> if the caller knows that this list does not contain
321     * any null elements.)
322     *
323     * <p>Like the {@link #toArray()} method, this method acts as bridge between
324     * array-based and collection-based APIs. Further, this method allows
325     * precise control over the runtime type of the output array, and may,
326     * under certain circumstances, be used to save allocation costs.
327     *
328 jsr166 1.92 * <p>Suppose {@code x} is a list known to contain only strings.
329 jsr166 1.35 * The following code can be used to dump the list into a newly
330 jsr166 1.92 * allocated array of {@code String}:
331 jsr166 1.35 *
332 jsr166 1.127 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
333 jsr166 1.35 *
334 jsr166 1.92 * Note that {@code toArray(new Object[0])} is identical in function to
335     * {@code toArray()}.
336 tim 1.1 *
337     * @param a the array into which the elements of the list are to
338 jsr166 1.35 * be stored, if it is big enough; otherwise, a new array of the
339     * same runtime type is allocated for this purpose.
340     * @return an array containing all the elements in this list
341     * @throws ArrayStoreException if the runtime type of the specified array
342     * is not a supertype of the runtime type of every element in
343     * this list
344     * @throws NullPointerException if the specified array is null
345 tim 1.1 */
346 jsr166 1.66 @SuppressWarnings("unchecked")
347 jsr166 1.114 public <T> T[] toArray(T[] a) {
348 dl 1.41 Object[] elements = getArray();
349 dl 1.40 int len = elements.length;
350     if (a.length < len)
351 jsr166 1.67 return (T[]) Arrays.copyOf(elements, len, a.getClass());
352     else {
353     System.arraycopy(elements, 0, a, 0, len);
354     if (a.length > len)
355     a[len] = null;
356     return a;
357     }
358 tim 1.1 }
359    
360     // Positional Access Operations
361    
362 jsr166 1.66 @SuppressWarnings("unchecked")
363     private E get(Object[] a, int index) {
364 jsr166 1.67 return (E) a[index];
365 jsr166 1.66 }
366    
367 jsr166 1.125 static String outOfBounds(int index, int size) {
368     return "Index: " + index + ", Size: " + size;
369     }
370    
371 tim 1.1 /**
372 jsr166 1.35 * {@inheritDoc}
373 tim 1.1 *
374 jsr166 1.35 * @throws IndexOutOfBoundsException {@inheritDoc}
375 tim 1.1 */
376     public E get(int index) {
377 jsr166 1.66 return get(getArray(), index);
378 tim 1.1 }
379    
380     /**
381 jsr166 1.35 * Replaces the element at the specified position in this list with the
382     * specified element.
383 tim 1.1 *
384 jsr166 1.35 * @throws IndexOutOfBoundsException {@inheritDoc}
385 tim 1.1 */
386 dl 1.42 public E set(int index, E element) {
387 jsr166 1.124 synchronized (lock) {
388 jsr166 1.67 Object[] elements = getArray();
389     E oldValue = get(elements, index);
390    
391     if (oldValue != element) {
392     int len = elements.length;
393     Object[] newElements = Arrays.copyOf(elements, len);
394     newElements[index] = element;
395     setArray(newElements);
396     } else {
397     // Not quite a no-op; ensures volatile write semantics
398     setArray(elements);
399     }
400     return oldValue;
401     }
402 tim 1.1 }
403    
404     /**
405     * Appends the specified element to the end of this list.
406     *
407 dl 1.40 * @param e element to be appended to this list
408 jsr166 1.92 * @return {@code true} (as specified by {@link Collection#add})
409 tim 1.1 */
410 dl 1.42 public boolean add(E e) {
411 jsr166 1.124 synchronized (lock) {
412 jsr166 1.67 Object[] elements = getArray();
413     int len = elements.length;
414     Object[] newElements = Arrays.copyOf(elements, len + 1);
415     newElements[len] = e;
416     setArray(newElements);
417     return true;
418     }
419 tim 1.1 }
420    
421     /**
422     * Inserts the specified element at the specified position in this
423     * list. Shifts the element currently at that position (if any) and
424     * any subsequent elements to the right (adds one to their indices).
425     *
426 jsr166 1.35 * @throws IndexOutOfBoundsException {@inheritDoc}
427 tim 1.1 */
428 dl 1.42 public void add(int index, E element) {
429 jsr166 1.124 synchronized (lock) {
430 jsr166 1.67 Object[] elements = getArray();
431     int len = elements.length;
432     if (index > len || index < 0)
433 jsr166 1.125 throw new IndexOutOfBoundsException(outOfBounds(index, len));
434 jsr166 1.67 Object[] newElements;
435     int numMoved = len - index;
436     if (numMoved == 0)
437     newElements = Arrays.copyOf(elements, len + 1);
438     else {
439     newElements = new Object[len + 1];
440     System.arraycopy(elements, 0, newElements, 0, index);
441     System.arraycopy(elements, index, newElements, index + 1,
442     numMoved);
443     }
444     newElements[index] = element;
445     setArray(newElements);
446     }
447 tim 1.1 }
448    
449     /**
450     * Removes the element at the specified position in this list.
451     * Shifts any subsequent elements to the left (subtracts one from their
452 jsr166 1.35 * indices). Returns the element that was removed from the list.
453 tim 1.1 *
454 jsr166 1.35 * @throws IndexOutOfBoundsException {@inheritDoc}
455 tim 1.1 */
456 dl 1.42 public E remove(int index) {
457 jsr166 1.124 synchronized (lock) {
458 jsr166 1.67 Object[] elements = getArray();
459     int len = elements.length;
460     E oldValue = get(elements, index);
461     int numMoved = len - index - 1;
462     if (numMoved == 0)
463     setArray(Arrays.copyOf(elements, len - 1));
464     else {
465     Object[] newElements = new Object[len - 1];
466     System.arraycopy(elements, 0, newElements, 0, index);
467     System.arraycopy(elements, index + 1, newElements, index,
468     numMoved);
469     setArray(newElements);
470     }
471     return oldValue;
472     }
473 tim 1.1 }
474    
475     /**
476 jsr166 1.35 * Removes the first occurrence of the specified element from this list,
477     * if it is present. If this list does not contain the element, it is
478     * unchanged. More formally, removes the element with the lowest index
479 jsr166 1.116 * {@code i} such that {@code Objects.equals(o, get(i))}
480 jsr166 1.92 * (if such an element exists). Returns {@code true} if this list
481 jsr166 1.35 * contained the specified element (or equivalently, if this list
482     * changed as a result of the call).
483 tim 1.1 *
484 jsr166 1.35 * @param o element to be removed from this list, if present
485 jsr166 1.92 * @return {@code true} if this list contained the specified element
486 tim 1.1 */
487 dl 1.42 public boolean remove(Object o) {
488 jsr166 1.104 Object[] snapshot = getArray();
489     int index = indexOf(o, snapshot, 0, snapshot.length);
490     return (index < 0) ? false : remove(o, snapshot, index);
491     }
492    
493     /**
494     * A version of remove(Object) using the strong hint that given
495     * recent snapshot contains o at the given index.
496     */
497     private boolean remove(Object o, Object[] snapshot, int index) {
498 jsr166 1.124 synchronized (lock) {
499 jsr166 1.104 Object[] current = getArray();
500     int len = current.length;
501     if (snapshot != current) findIndex: {
502     int prefix = Math.min(index, len);
503     for (int i = 0; i < prefix; i++) {
504 jsr166 1.129 if (current[i] != snapshot[i]
505     && Objects.equals(o, current[i])) {
506 jsr166 1.104 index = i;
507     break findIndex;
508     }
509 jsr166 1.67 }
510 jsr166 1.104 if (index >= len)
511     return false;
512     if (current[index] == o)
513     break findIndex;
514     index = indexOf(o, current, index, len);
515     if (index < 0)
516     return false;
517 jsr166 1.67 }
518 jsr166 1.104 Object[] newElements = new Object[len - 1];
519     System.arraycopy(current, 0, newElements, 0, index);
520     System.arraycopy(current, index + 1,
521     newElements, index,
522     len - index - 1);
523     setArray(newElements);
524     return true;
525 jsr166 1.67 }
526 tim 1.1 }
527    
528     /**
529 jsr166 1.35 * Removes from this list all of the elements whose index is between
530 jsr166 1.92 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
531 jsr166 1.35 * Shifts any succeeding elements to the left (reduces their index).
532 jsr166 1.92 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
533     * (If {@code toIndex==fromIndex}, this operation has no effect.)
534 tim 1.1 *
535 jsr166 1.35 * @param fromIndex index of first element to be removed
536     * @param toIndex index after last element to be removed
537 jsr166 1.66 * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range
538 jsr166 1.86 * ({@code fromIndex < 0 || toIndex > size() || toIndex < fromIndex})
539 tim 1.1 */
540 jsr166 1.84 void removeRange(int fromIndex, int toIndex) {
541 jsr166 1.124 synchronized (lock) {
542 jsr166 1.67 Object[] elements = getArray();
543     int len = elements.length;
544    
545     if (fromIndex < 0 || toIndex > len || toIndex < fromIndex)
546     throw new IndexOutOfBoundsException();
547     int newlen = len - (toIndex - fromIndex);
548     int numMoved = len - toIndex;
549     if (numMoved == 0)
550     setArray(Arrays.copyOf(elements, newlen));
551     else {
552     Object[] newElements = new Object[newlen];
553     System.arraycopy(elements, 0, newElements, 0, fromIndex);
554     System.arraycopy(elements, toIndex, newElements,
555     fromIndex, numMoved);
556     setArray(newElements);
557     }
558     }
559 tim 1.1 }
560    
561     /**
562 jsr166 1.90 * Appends the element, if not present.
563 jsr166 1.38 *
564 dl 1.40 * @param e element to be added to this list, if absent
565 jsr166 1.92 * @return {@code true} if the element was added
566 jsr166 1.30 */
567 dl 1.42 public boolean addIfAbsent(E e) {
568 jsr166 1.104 Object[] snapshot = getArray();
569     return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
570     addIfAbsent(e, snapshot);
571     }
572    
573     /**
574     * A version of addIfAbsent using the strong hint that given
575     * recent snapshot does not contain e.
576     */
577     private boolean addIfAbsent(E e, Object[] snapshot) {
578 jsr166 1.124 synchronized (lock) {
579 jsr166 1.104 Object[] current = getArray();
580     int len = current.length;
581     if (snapshot != current) {
582     // Optimize for lost race to another addXXX operation
583     int common = Math.min(snapshot.length, len);
584     for (int i = 0; i < common; i++)
585 jsr166 1.129 if (current[i] != snapshot[i]
586     && Objects.equals(e, current[i]))
587 jsr166 1.104 return false;
588     if (indexOf(e, current, common, len) >= 0)
589     return false;
590 jsr166 1.67 }
591 jsr166 1.104 Object[] newElements = Arrays.copyOf(current, len + 1);
592 jsr166 1.67 newElements[len] = e;
593     setArray(newElements);
594     return true;
595     }
596 tim 1.1 }
597    
598     /**
599 jsr166 1.92 * Returns {@code true} if this list contains all of the elements of the
600 jsr166 1.32 * specified collection.
601 jsr166 1.34 *
602 jsr166 1.36 * @param c collection to be checked for containment in this list
603 jsr166 1.92 * @return {@code true} if this list contains all of the elements of the
604 jsr166 1.35 * specified collection
605     * @throws NullPointerException if the specified collection is null
606 jsr166 1.38 * @see #contains(Object)
607 tim 1.1 */
608 tim 1.7 public boolean containsAll(Collection<?> c) {
609 dl 1.41 Object[] elements = getArray();
610 dl 1.40 int len = elements.length;
611 jsr166 1.67 for (Object e : c) {
612 dl 1.41 if (indexOf(e, elements, 0, len) < 0)
613 tim 1.1 return false;
614 jsr166 1.67 }
615 tim 1.1 return true;
616     }
617    
618     /**
619 jsr166 1.32 * Removes from this list all of its elements that are contained in
620     * the specified collection. This is a particularly expensive operation
621 tim 1.1 * in this class because of the need for an internal temporary array.
622     *
623 jsr166 1.35 * @param c collection containing elements to be removed from this list
624 jsr166 1.92 * @return {@code true} if this list changed as a result of the call
625 jsr166 1.38 * @throws ClassCastException if the class of an element of this list
626 dl 1.73 * is incompatible with the specified collection
627 dl 1.74 * (<a href="../Collection.html#optional-restrictions">optional</a>)
628 jsr166 1.38 * @throws NullPointerException if this list contains a null element and the
629 dl 1.73 * specified collection does not permit null elements
630 dl 1.75 * (<a href="../Collection.html#optional-restrictions">optional</a>),
631 jsr166 1.38 * or if the specified collection is null
632     * @see #remove(Object)
633 tim 1.1 */
634 dl 1.42 public boolean removeAll(Collection<?> c) {
635 dl 1.88 if (c == null) throw new NullPointerException();
636 jsr166 1.124 synchronized (lock) {
637 jsr166 1.67 Object[] elements = getArray();
638     int len = elements.length;
639     if (len != 0) {
640     // temp array holds those elements we know we want to keep
641     int newlen = 0;
642     Object[] temp = new Object[len];
643     for (int i = 0; i < len; ++i) {
644     Object element = elements[i];
645     if (!c.contains(element))
646     temp[newlen++] = element;
647     }
648     if (newlen != len) {
649     setArray(Arrays.copyOf(temp, newlen));
650     return true;
651     }
652     }
653     return false;
654     }
655 tim 1.1 }
656    
657     /**
658 jsr166 1.32 * Retains only the elements in this list that are contained in the
659 jsr166 1.35 * specified collection. In other words, removes from this list all of
660     * its elements that are not contained in the specified collection.
661 jsr166 1.32 *
662 jsr166 1.35 * @param c collection containing elements to be retained in this list
663 jsr166 1.92 * @return {@code true} if this list changed as a result of the call
664 jsr166 1.38 * @throws ClassCastException if the class of an element of this list
665 dl 1.73 * is incompatible with the specified collection
666 dl 1.74 * (<a href="../Collection.html#optional-restrictions">optional</a>)
667 jsr166 1.38 * @throws NullPointerException if this list contains a null element and the
668 dl 1.73 * specified collection does not permit null elements
669 dl 1.75 * (<a href="../Collection.html#optional-restrictions">optional</a>),
670 jsr166 1.38 * or if the specified collection is null
671     * @see #remove(Object)
672 tim 1.1 */
673 dl 1.42 public boolean retainAll(Collection<?> c) {
674 dl 1.88 if (c == null) throw new NullPointerException();
675 jsr166 1.124 synchronized (lock) {
676 jsr166 1.67 Object[] elements = getArray();
677     int len = elements.length;
678     if (len != 0) {
679     // temp array holds those elements we know we want to keep
680     int newlen = 0;
681     Object[] temp = new Object[len];
682     for (int i = 0; i < len; ++i) {
683     Object element = elements[i];
684     if (c.contains(element))
685     temp[newlen++] = element;
686     }
687     if (newlen != len) {
688     setArray(Arrays.copyOf(temp, newlen));
689     return true;
690     }
691     }
692     return false;
693     }
694 tim 1.1 }
695    
696     /**
697 jsr166 1.32 * Appends all of the elements in the specified collection that
698 tim 1.1 * are not already contained in this list, to the end of
699     * this list, in the order that they are returned by the
700 jsr166 1.32 * specified collection's iterator.
701 tim 1.1 *
702 jsr166 1.36 * @param c collection containing elements to be added to this list
703 tim 1.1 * @return the number of elements added
704 jsr166 1.35 * @throws NullPointerException if the specified collection is null
705 jsr166 1.38 * @see #addIfAbsent(Object)
706 tim 1.1 */
707 dl 1.42 public int addAllAbsent(Collection<? extends E> c) {
708 jsr166 1.67 Object[] cs = c.toArray();
709     if (cs.length == 0)
710     return 0;
711 jsr166 1.124 synchronized (lock) {
712 jsr166 1.67 Object[] elements = getArray();
713     int len = elements.length;
714     int added = 0;
715 jsr166 1.103 // uniquify and compact elements in cs
716     for (int i = 0; i < cs.length; ++i) {
717 jsr166 1.67 Object e = cs[i];
718     if (indexOf(e, elements, 0, len) < 0 &&
719 jsr166 1.103 indexOf(e, cs, 0, added) < 0)
720     cs[added++] = e;
721 jsr166 1.67 }
722     if (added > 0) {
723     Object[] newElements = Arrays.copyOf(elements, len + added);
724 jsr166 1.103 System.arraycopy(cs, 0, newElements, len, added);
725 jsr166 1.67 setArray(newElements);
726     }
727     return added;
728     }
729 tim 1.1 }
730    
731     /**
732     * Removes all of the elements from this list.
733 jsr166 1.38 * The list will be empty after this call returns.
734 tim 1.1 */
735 dl 1.42 public void clear() {
736 jsr166 1.124 synchronized (lock) {
737 jsr166 1.67 setArray(new Object[0]);
738     }
739 tim 1.1 }
740    
741     /**
742 jsr166 1.32 * Appends all of the elements in the specified collection to the end
743     * of this list, in the order that they are returned by the specified
744     * collection's iterator.
745 tim 1.1 *
746 jsr166 1.36 * @param c collection containing elements to be added to this list
747 jsr166 1.92 * @return {@code true} if this list changed as a result of the call
748 jsr166 1.35 * @throws NullPointerException if the specified collection is null
749 jsr166 1.38 * @see #add(Object)
750 tim 1.1 */
751 dl 1.42 public boolean addAll(Collection<? extends E> c) {
752 dl 1.106 Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
753     ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
754 jsr166 1.67 if (cs.length == 0)
755     return false;
756 jsr166 1.124 synchronized (lock) {
757 jsr166 1.67 Object[] elements = getArray();
758     int len = elements.length;
759 dl 1.106 if (len == 0 && cs.getClass() == Object[].class)
760     setArray(cs);
761     else {
762     Object[] newElements = Arrays.copyOf(elements, len + cs.length);
763     System.arraycopy(cs, 0, newElements, len, cs.length);
764     setArray(newElements);
765     }
766 jsr166 1.67 return true;
767     }
768 tim 1.1 }
769    
770     /**
771 jsr166 1.35 * Inserts all of the elements in the specified collection into this
772 tim 1.1 * list, starting at the specified position. Shifts the element
773     * currently at that position (if any) and any subsequent elements to
774     * the right (increases their indices). The new elements will appear
775 jsr166 1.38 * in this list in the order that they are returned by the
776     * specified collection's iterator.
777 tim 1.1 *
778 jsr166 1.35 * @param index index at which to insert the first element
779     * from the specified collection
780 jsr166 1.36 * @param c collection containing elements to be added to this list
781 jsr166 1.92 * @return {@code true} if this list changed as a result of the call
782 jsr166 1.35 * @throws IndexOutOfBoundsException {@inheritDoc}
783     * @throws NullPointerException if the specified collection is null
784 jsr166 1.38 * @see #add(int,Object)
785 tim 1.1 */
786 dl 1.42 public boolean addAll(int index, Collection<? extends E> c) {
787 jsr166 1.67 Object[] cs = c.toArray();
788 jsr166 1.124 synchronized (lock) {
789 jsr166 1.67 Object[] elements = getArray();
790     int len = elements.length;
791     if (index > len || index < 0)
792 jsr166 1.125 throw new IndexOutOfBoundsException(outOfBounds(index, len));
793 jsr166 1.67 if (cs.length == 0)
794     return false;
795     int numMoved = len - index;
796     Object[] newElements;
797     if (numMoved == 0)
798     newElements = Arrays.copyOf(elements, len + cs.length);
799     else {
800     newElements = new Object[len + cs.length];
801     System.arraycopy(elements, 0, newElements, 0, index);
802     System.arraycopy(elements, index,
803     newElements, index + cs.length,
804     numMoved);
805     }
806     System.arraycopy(cs, 0, newElements, index, cs.length);
807     setArray(newElements);
808     return true;
809     }
810 tim 1.1 }
811    
812 dl 1.106 public void forEach(Consumer<? super E> action) {
813     if (action == null) throw new NullPointerException();
814 jsr166 1.126 for (Object x : getArray()) {
815     @SuppressWarnings("unchecked") E e = (E) x;
816 dl 1.106 action.accept(e);
817     }
818     }
819    
820     public boolean removeIf(Predicate<? super E> filter) {
821     if (filter == null) throw new NullPointerException();
822 jsr166 1.124 synchronized (lock) {
823 dl 1.106 Object[] elements = getArray();
824     int len = elements.length;
825     if (len != 0) {
826     int newlen = 0;
827     Object[] temp = new Object[len];
828     for (int i = 0; i < len; ++i) {
829     @SuppressWarnings("unchecked") E e = (E) elements[i];
830     if (!filter.test(e))
831     temp[newlen++] = e;
832     }
833     if (newlen != len) {
834     setArray(Arrays.copyOf(temp, newlen));
835     return true;
836     }
837     }
838     return false;
839     }
840     }
841    
842     public void replaceAll(UnaryOperator<E> operator) {
843 dl 1.108 if (operator == null) throw new NullPointerException();
844 jsr166 1.124 synchronized (lock) {
845 dl 1.106 Object[] elements = getArray();
846     int len = elements.length;
847     Object[] newElements = Arrays.copyOf(elements, len);
848     for (int i = 0; i < len; ++i) {
849     @SuppressWarnings("unchecked") E e = (E) elements[i];
850     newElements[i] = operator.apply(e);
851     }
852     setArray(newElements);
853     }
854     }
855    
856     public void sort(Comparator<? super E> c) {
857 jsr166 1.124 synchronized (lock) {
858 jsr166 1.107 Object[] elements = getArray();
859     Object[] newElements = Arrays.copyOf(elements, elements.length);
860     @SuppressWarnings("unchecked") E[] es = (E[])newElements;
861     Arrays.sort(es, c);
862     setArray(newElements);
863 dl 1.106 }
864     }
865    
866 tim 1.1 /**
867 jsr166 1.87 * Saves this list to a stream (that is, serializes it).
868 tim 1.1 *
869 jsr166 1.111 * @param s the stream
870 jsr166 1.112 * @throws java.io.IOException if an I/O error occurs
871 tim 1.1 * @serialData The length of the array backing the list is emitted
872     * (int), followed by all of its elements (each an Object)
873     * in the proper order.
874     */
875     private void writeObject(java.io.ObjectOutputStream s)
876 jsr166 1.85 throws java.io.IOException {
877 tim 1.1
878     s.defaultWriteObject();
879    
880 dl 1.41 Object[] elements = getArray();
881 tim 1.1 // Write out array length
882 jsr166 1.71 s.writeInt(elements.length);
883 tim 1.1
884     // Write out all elements in the proper order.
885 jsr166 1.71 for (Object element : elements)
886     s.writeObject(element);
887 tim 1.1 }
888    
889     /**
890 jsr166 1.87 * Reconstitutes this list from a stream (that is, deserializes it).
891 jsr166 1.111 * @param s the stream
892 jsr166 1.112 * @throws ClassNotFoundException if the class of a serialized object
893     * could not be found
894     * @throws java.io.IOException if an I/O error occurs
895 tim 1.1 */
896 dl 1.12 private void readObject(java.io.ObjectInputStream s)
897 tim 1.1 throws java.io.IOException, ClassNotFoundException {
898    
899     s.defaultReadObject();
900    
901 dl 1.42 // bind to new lock
902     resetLock();
903    
904 tim 1.1 // Read in array length and allocate array
905 dl 1.40 int len = s.readInt();
906 dl 1.41 Object[] elements = new Object[len];
907 tim 1.1
908     // Read in all elements in the proper order.
909 dl 1.40 for (int i = 0; i < len; i++)
910 dl 1.41 elements[i] = s.readObject();
911 dl 1.40 setArray(elements);
912 tim 1.1 }
913    
914     /**
915 jsr166 1.55 * Returns a string representation of this list. The string
916     * representation consists of the string representations of the list's
917     * elements in the order they are returned by its iterator, enclosed in
918 jsr166 1.92 * square brackets ({@code "[]"}). Adjacent elements are separated by
919     * the characters {@code ", "} (comma and space). Elements are
920 jsr166 1.55 * converted to strings as by {@link String#valueOf(Object)}.
921     *
922     * @return a string representation of this list
923 tim 1.1 */
924     public String toString() {
925 jsr166 1.67 return Arrays.toString(getArray());
926 tim 1.1 }
927    
928     /**
929 jsr166 1.35 * Compares the specified object with this list for equality.
930 jsr166 1.60 * Returns {@code true} if the specified object is the same object
931     * as this object, or if it is also a {@link List} and the sequence
932     * of elements returned by an {@linkplain List#iterator() iterator}
933     * over the specified list is the same as the sequence returned by
934     * an iterator over this list. The two sequences are considered to
935     * be the same if they have the same length and corresponding
936     * elements at the same position in the sequence are <em>equal</em>.
937     * Two elements {@code e1} and {@code e2} are considered
938 jsr166 1.117 * <em>equal</em> if {@code Objects.equals(e1, e2)}.
939 tim 1.1 *
940 jsr166 1.35 * @param o the object to be compared for equality with this list
941 jsr166 1.60 * @return {@code true} if the specified object is equal to this list
942 tim 1.1 */
943     public boolean equals(Object o) {
944     if (o == this)
945     return true;
946     if (!(o instanceof List))
947     return false;
948    
949 jsr166 1.121 List<?> list = (List<?>)o;
950 jsr166 1.67 Iterator<?> it = list.iterator();
951     Object[] elements = getArray();
952 jsr166 1.129 for (int i = 0, len = elements.length; i < len; i++)
953     if (!it.hasNext() || !Objects.equals(elements[i], it.next()))
954 dl 1.57 return false;
955 jsr166 1.60 if (it.hasNext())
956 tim 1.1 return false;
957     return true;
958     }
959    
960     /**
961 jsr166 1.35 * Returns the hash code value for this list.
962 dl 1.26 *
963 jsr166 1.47 * <p>This implementation uses the definition in {@link List#hashCode}.
964     *
965     * @return the hash code value for this list
966 tim 1.1 */
967     public int hashCode() {
968     int hashCode = 1;
969 jsr166 1.126 for (Object x : getArray())
970     hashCode = 31 * hashCode + (x == null ? 0 : x.hashCode());
971 tim 1.1 return hashCode;
972     }
973    
974     /**
975 jsr166 1.35 * Returns an iterator over the elements in this list in proper sequence.
976     *
977     * <p>The returned iterator provides a snapshot of the state of the list
978     * when the iterator was constructed. No synchronization is needed while
979     * traversing the iterator. The iterator does <em>NOT</em> support the
980 jsr166 1.92 * {@code remove} method.
981 jsr166 1.35 *
982     * @return an iterator over the elements in this list in proper sequence
983 tim 1.1 */
984     public Iterator<E> iterator() {
985 dl 1.40 return new COWIterator<E>(getArray(), 0);
986 tim 1.1 }
987    
988     /**
989 jsr166 1.35 * {@inheritDoc}
990 tim 1.1 *
991 jsr166 1.35 * <p>The returned iterator provides a snapshot of the state of the list
992     * when the iterator was constructed. No synchronization is needed while
993     * traversing the iterator. The iterator does <em>NOT</em> support the
994 jsr166 1.92 * {@code remove}, {@code set} or {@code add} methods.
995 tim 1.1 */
996     public ListIterator<E> listIterator() {
997 dl 1.40 return new COWIterator<E>(getArray(), 0);
998 tim 1.1 }
999    
1000     /**
1001 jsr166 1.35 * {@inheritDoc}
1002     *
1003 jsr166 1.50 * <p>The returned iterator provides a snapshot of the state of the list
1004     * when the iterator was constructed. No synchronization is needed while
1005     * traversing the iterator. The iterator does <em>NOT</em> support the
1006 jsr166 1.92 * {@code remove}, {@code set} or {@code add} methods.
1007 jsr166 1.35 *
1008     * @throws IndexOutOfBoundsException {@inheritDoc}
1009 tim 1.1 */
1010 jsr166 1.110 public ListIterator<E> listIterator(int index) {
1011 dl 1.41 Object[] elements = getArray();
1012 dl 1.40 int len = elements.length;
1013 jsr166 1.109 if (index < 0 || index > len)
1014 jsr166 1.125 throw new IndexOutOfBoundsException(outOfBounds(index, len));
1015 tim 1.1
1016 dl 1.48 return new COWIterator<E>(elements, index);
1017 tim 1.1 }
1018    
1019 jsr166 1.113 /**
1020     * Returns a {@link Spliterator} over the elements in this list.
1021     *
1022     * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
1023     * {@link Spliterator#ORDERED}, {@link Spliterator#SIZED}, and
1024     * {@link Spliterator#SUBSIZED}.
1025     *
1026     * <p>The spliterator provides a snapshot of the state of the list
1027     * when the spliterator was constructed. No synchronization is needed while
1028     * operating on the spliterator. The spliterator does <em>NOT</em> support
1029     * the {@code remove}, {@code set} or {@code add} methods.
1030     *
1031     * @return a {@code Spliterator} over the elements in this list
1032     * @since 1.8
1033     */
1034 dl 1.100 public Spliterator<E> spliterator() {
1035 dl 1.99 return Spliterators.spliterator
1036 dl 1.98 (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED);
1037     }
1038    
1039 dl 1.93 static final class COWIterator<E> implements ListIterator<E> {
1040 jsr166 1.68 /** Snapshot of the array */
1041 dl 1.41 private final Object[] snapshot;
1042 dl 1.40 /** Index of element to be returned by subsequent call to next. */
1043 tim 1.1 private int cursor;
1044    
1045 jsr166 1.128 COWIterator(Object[] elements, int initialCursor) {
1046 tim 1.1 cursor = initialCursor;
1047 dl 1.40 snapshot = elements;
1048 tim 1.1 }
1049    
1050     public boolean hasNext() {
1051 dl 1.40 return cursor < snapshot.length;
1052 tim 1.1 }
1053    
1054     public boolean hasPrevious() {
1055     return cursor > 0;
1056     }
1057    
1058 jsr166 1.67 @SuppressWarnings("unchecked")
1059 tim 1.1 public E next() {
1060 jsr166 1.67 if (! hasNext())
1061 tim 1.1 throw new NoSuchElementException();
1062 jsr166 1.67 return (E) snapshot[cursor++];
1063 tim 1.1 }
1064    
1065 jsr166 1.67 @SuppressWarnings("unchecked")
1066 tim 1.1 public E previous() {
1067 jsr166 1.67 if (! hasPrevious())
1068 tim 1.1 throw new NoSuchElementException();
1069 jsr166 1.67 return (E) snapshot[--cursor];
1070 tim 1.1 }
1071    
1072     public int nextIndex() {
1073     return cursor;
1074     }
1075    
1076     public int previousIndex() {
1077 jsr166 1.45 return cursor-1;
1078 tim 1.1 }
1079    
1080     /**
1081     * Not supported. Always throws UnsupportedOperationException.
1082 jsr166 1.92 * @throws UnsupportedOperationException always; {@code remove}
1083 jsr166 1.32 * is not supported by this iterator.
1084 tim 1.1 */
1085     public void remove() {
1086     throw new UnsupportedOperationException();
1087     }
1088    
1089     /**
1090     * Not supported. Always throws UnsupportedOperationException.
1091 jsr166 1.92 * @throws UnsupportedOperationException always; {@code set}
1092 jsr166 1.32 * is not supported by this iterator.
1093 tim 1.1 */
1094 jsr166 1.33 public void set(E e) {
1095 tim 1.1 throw new UnsupportedOperationException();
1096     }
1097    
1098     /**
1099     * Not supported. Always throws UnsupportedOperationException.
1100 jsr166 1.92 * @throws UnsupportedOperationException always; {@code add}
1101 jsr166 1.32 * is not supported by this iterator.
1102 tim 1.1 */
1103 jsr166 1.33 public void add(E e) {
1104 tim 1.1 throw new UnsupportedOperationException();
1105     }
1106     }
1107    
1108     /**
1109 dl 1.40 * Returns a view of the portion of this list between
1110 jsr166 1.92 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1111 dl 1.40 * The returned list is backed by this list, so changes in the
1112 jsr166 1.66 * returned list are reflected in this list.
1113 dl 1.40 *
1114     * <p>The semantics of the list returned by this method become
1115 jsr166 1.66 * undefined if the backing list (i.e., this list) is modified in
1116     * any way other than via the returned list.
1117 tim 1.1 *
1118 jsr166 1.35 * @param fromIndex low endpoint (inclusive) of the subList
1119     * @param toIndex high endpoint (exclusive) of the subList
1120     * @return a view of the specified range within this list
1121     * @throws IndexOutOfBoundsException {@inheritDoc}
1122 tim 1.1 */
1123 dl 1.42 public List<E> subList(int fromIndex, int toIndex) {
1124 jsr166 1.124 synchronized (lock) {
1125 jsr166 1.67 Object[] elements = getArray();
1126     int len = elements.length;
1127     if (fromIndex < 0 || toIndex > len || fromIndex > toIndex)
1128     throw new IndexOutOfBoundsException();
1129     return new COWSubList<E>(this, fromIndex, toIndex);
1130     }
1131 tim 1.1 }
1132    
1133 dl 1.42 /**
1134     * Sublist for CopyOnWriteArrayList.
1135     * This class extends AbstractList merely for convenience, to
1136     * avoid having to define addAll, etc. This doesn't hurt, but
1137     * is wasteful. This class does not need or use modCount
1138     * mechanics in AbstractList, but does need to check for
1139     * concurrent modification using similar mechanics. On each
1140     * operation, the array that we expect the backing list to use
1141     * is checked and updated. Since we do this for all of the
1142     * base operations invoked by those defined in AbstractList,
1143     * all is well. While inefficient, this is not worth
1144     * improving. The kinds of list operations inherited from
1145     * AbstractList are already so slow on COW sublists that
1146     * adding a bit more space/time doesn't seem even noticeable.
1147     */
1148 jsr166 1.66 private static class COWSubList<E>
1149 jsr166 1.67 extends AbstractList<E>
1150     implements RandomAccess
1151 jsr166 1.66 {
1152 tim 1.1 private final CopyOnWriteArrayList<E> l;
1153     private final int offset;
1154     private int size;
1155 dl 1.41 private Object[] expectedArray;
1156 tim 1.1
1157 jsr166 1.45 // only call this holding l's lock
1158 jsr166 1.66 COWSubList(CopyOnWriteArrayList<E> list,
1159 jsr166 1.67 int fromIndex, int toIndex) {
1160 jsr166 1.124 // assert Thread.holdsLock(list.lock);
1161 tim 1.1 l = list;
1162 dl 1.40 expectedArray = l.getArray();
1163 tim 1.1 offset = fromIndex;
1164     size = toIndex - fromIndex;
1165     }
1166    
1167     // only call this holding l's lock
1168     private void checkForComodification() {
1169 jsr166 1.124 // assert Thread.holdsLock(l.lock);
1170 dl 1.40 if (l.getArray() != expectedArray)
1171 tim 1.1 throw new ConcurrentModificationException();
1172     }
1173    
1174     // only call this holding l's lock
1175     private void rangeCheck(int index) {
1176 jsr166 1.124 // assert Thread.holdsLock(l.lock);
1177 jsr166 1.109 if (index < 0 || index >= size)
1178 jsr166 1.125 throw new IndexOutOfBoundsException(outOfBounds(index, size));
1179 tim 1.1 }
1180    
1181     public E set(int index, E element) {
1182 jsr166 1.124 synchronized (l.lock) {
1183 tim 1.1 rangeCheck(index);
1184     checkForComodification();
1185 jsr166 1.45 E x = l.set(index+offset, element);
1186 dl 1.40 expectedArray = l.getArray();
1187 tim 1.1 return x;
1188 jsr166 1.67 }
1189 tim 1.1 }
1190    
1191     public E get(int index) {
1192 jsr166 1.124 synchronized (l.lock) {
1193 tim 1.1 rangeCheck(index);
1194     checkForComodification();
1195 jsr166 1.45 return l.get(index+offset);
1196 jsr166 1.67 }
1197 tim 1.1 }
1198    
1199     public int size() {
1200 jsr166 1.124 synchronized (l.lock) {
1201 tim 1.1 checkForComodification();
1202     return size;
1203 jsr166 1.67 }
1204 tim 1.1 }
1205    
1206     public void add(int index, E element) {
1207 jsr166 1.124 synchronized (l.lock) {
1208 tim 1.1 checkForComodification();
1209 jsr166 1.109 if (index < 0 || index > size)
1210 jsr166 1.125 throw new IndexOutOfBoundsException
1211     (outOfBounds(index, size));
1212 jsr166 1.45 l.add(index+offset, element);
1213 dl 1.40 expectedArray = l.getArray();
1214 tim 1.1 size++;
1215 jsr166 1.67 }
1216 tim 1.1 }
1217    
1218 dl 1.13 public void clear() {
1219 jsr166 1.124 synchronized (l.lock) {
1220 dl 1.13 checkForComodification();
1221     l.removeRange(offset, offset+size);
1222 dl 1.40 expectedArray = l.getArray();
1223 dl 1.13 size = 0;
1224 jsr166 1.67 }
1225 dl 1.13 }
1226    
1227 tim 1.1 public E remove(int index) {
1228 jsr166 1.124 synchronized (l.lock) {
1229 tim 1.1 rangeCheck(index);
1230     checkForComodification();
1231 jsr166 1.45 E result = l.remove(index+offset);
1232 dl 1.40 expectedArray = l.getArray();
1233 tim 1.1 size--;
1234     return result;
1235 jsr166 1.67 }
1236 tim 1.1 }
1237    
1238 jsr166 1.66 public boolean remove(Object o) {
1239 jsr166 1.67 int index = indexOf(o);
1240     if (index == -1)
1241     return false;
1242     remove(index);
1243     return true;
1244 jsr166 1.66 }
1245    
1246 tim 1.1 public Iterator<E> iterator() {
1247 jsr166 1.124 synchronized (l.lock) {
1248 tim 1.1 checkForComodification();
1249 tim 1.8 return new COWSubListIterator<E>(l, 0, offset, size);
1250 jsr166 1.67 }
1251 tim 1.1 }
1252    
1253 jsr166 1.110 public ListIterator<E> listIterator(int index) {
1254 jsr166 1.124 synchronized (l.lock) {
1255 tim 1.1 checkForComodification();
1256 jsr166 1.109 if (index < 0 || index > size)
1257 jsr166 1.125 throw new IndexOutOfBoundsException
1258     (outOfBounds(index, size));
1259 tim 1.8 return new COWSubListIterator<E>(l, index, offset, size);
1260 jsr166 1.67 }
1261 tim 1.1 }
1262    
1263 tim 1.7 public List<E> subList(int fromIndex, int toIndex) {
1264 jsr166 1.124 synchronized (l.lock) {
1265 tim 1.7 checkForComodification();
1266 jsr166 1.115 if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
1267 tim 1.7 throw new IndexOutOfBoundsException();
1268 dl 1.41 return new COWSubList<E>(l, fromIndex + offset,
1269 jsr166 1.67 toIndex + offset);
1270     }
1271 tim 1.7 }
1272 tim 1.1
1273 dl 1.106 public void forEach(Consumer<? super E> action) {
1274     if (action == null) throw new NullPointerException();
1275     int lo = offset;
1276     int hi = offset + size;
1277     Object[] a = expectedArray;
1278     if (l.getArray() != a)
1279     throw new ConcurrentModificationException();
1280 dl 1.108 if (lo < 0 || hi > a.length)
1281     throw new IndexOutOfBoundsException();
1282 dl 1.106 for (int i = lo; i < hi; ++i) {
1283     @SuppressWarnings("unchecked") E e = (E) a[i];
1284     action.accept(e);
1285     }
1286     }
1287    
1288 dl 1.108 public void replaceAll(UnaryOperator<E> operator) {
1289     if (operator == null) throw new NullPointerException();
1290 jsr166 1.124 synchronized (l.lock) {
1291 dl 1.108 int lo = offset;
1292     int hi = offset + size;
1293     Object[] elements = expectedArray;
1294     if (l.getArray() != elements)
1295     throw new ConcurrentModificationException();
1296     int len = elements.length;
1297     if (lo < 0 || hi > len)
1298     throw new IndexOutOfBoundsException();
1299     Object[] newElements = Arrays.copyOf(elements, len);
1300     for (int i = lo; i < hi; ++i) {
1301     @SuppressWarnings("unchecked") E e = (E) elements[i];
1302     newElements[i] = operator.apply(e);
1303     }
1304     l.setArray(expectedArray = newElements);
1305     }
1306     }
1307    
1308     public void sort(Comparator<? super E> c) {
1309 jsr166 1.124 synchronized (l.lock) {
1310 dl 1.108 int lo = offset;
1311     int hi = offset + size;
1312     Object[] elements = expectedArray;
1313     if (l.getArray() != elements)
1314     throw new ConcurrentModificationException();
1315     int len = elements.length;
1316     if (lo < 0 || hi > len)
1317     throw new IndexOutOfBoundsException();
1318     Object[] newElements = Arrays.copyOf(elements, len);
1319     @SuppressWarnings("unchecked") E[] es = (E[])newElements;
1320     Arrays.sort(es, lo, hi, c);
1321     l.setArray(expectedArray = newElements);
1322     }
1323     }
1324    
1325     public boolean removeAll(Collection<?> c) {
1326     if (c == null) throw new NullPointerException();
1327     boolean removed = false;
1328 jsr166 1.124 synchronized (l.lock) {
1329 dl 1.108 int n = size;
1330     if (n > 0) {
1331     int lo = offset;
1332     int hi = offset + n;
1333     Object[] elements = expectedArray;
1334     if (l.getArray() != elements)
1335     throw new ConcurrentModificationException();
1336     int len = elements.length;
1337     if (lo < 0 || hi > len)
1338     throw new IndexOutOfBoundsException();
1339     int newSize = 0;
1340     Object[] temp = new Object[n];
1341     for (int i = lo; i < hi; ++i) {
1342     Object element = elements[i];
1343     if (!c.contains(element))
1344     temp[newSize++] = element;
1345     }
1346     if (newSize != n) {
1347     Object[] newElements = new Object[len - n + newSize];
1348     System.arraycopy(elements, 0, newElements, 0, lo);
1349     System.arraycopy(temp, 0, newElements, lo, newSize);
1350     System.arraycopy(elements, hi, newElements,
1351     lo + newSize, len - hi);
1352     size = newSize;
1353     removed = true;
1354     l.setArray(expectedArray = newElements);
1355     }
1356     }
1357     }
1358     return removed;
1359     }
1360    
1361     public boolean retainAll(Collection<?> c) {
1362     if (c == null) throw new NullPointerException();
1363     boolean removed = false;
1364 jsr166 1.124 synchronized (l.lock) {
1365 dl 1.108 int n = size;
1366     if (n > 0) {
1367     int lo = offset;
1368     int hi = offset + n;
1369     Object[] elements = expectedArray;
1370     if (l.getArray() != elements)
1371     throw new ConcurrentModificationException();
1372     int len = elements.length;
1373     if (lo < 0 || hi > len)
1374     throw new IndexOutOfBoundsException();
1375     int newSize = 0;
1376     Object[] temp = new Object[n];
1377     for (int i = lo; i < hi; ++i) {
1378     Object element = elements[i];
1379     if (c.contains(element))
1380     temp[newSize++] = element;
1381     }
1382     if (newSize != n) {
1383     Object[] newElements = new Object[len - n + newSize];
1384     System.arraycopy(elements, 0, newElements, 0, lo);
1385     System.arraycopy(temp, 0, newElements, lo, newSize);
1386     System.arraycopy(elements, hi, newElements,
1387     lo + newSize, len - hi);
1388     size = newSize;
1389     removed = true;
1390     l.setArray(expectedArray = newElements);
1391     }
1392     }
1393     }
1394     return removed;
1395     }
1396    
1397     public boolean removeIf(Predicate<? super E> filter) {
1398     if (filter == null) throw new NullPointerException();
1399     boolean removed = false;
1400 jsr166 1.124 synchronized (l.lock) {
1401 dl 1.108 int n = size;
1402     if (n > 0) {
1403     int lo = offset;
1404     int hi = offset + n;
1405     Object[] elements = expectedArray;
1406     if (l.getArray() != elements)
1407     throw new ConcurrentModificationException();
1408     int len = elements.length;
1409     if (lo < 0 || hi > len)
1410     throw new IndexOutOfBoundsException();
1411     int newSize = 0;
1412     Object[] temp = new Object[n];
1413     for (int i = lo; i < hi; ++i) {
1414     @SuppressWarnings("unchecked") E e = (E) elements[i];
1415     if (!filter.test(e))
1416     temp[newSize++] = e;
1417     }
1418     if (newSize != n) {
1419     Object[] newElements = new Object[len - n + newSize];
1420     System.arraycopy(elements, 0, newElements, 0, lo);
1421     System.arraycopy(temp, 0, newElements, lo, newSize);
1422     System.arraycopy(elements, hi, newElements,
1423     lo + newSize, len - hi);
1424     size = newSize;
1425     removed = true;
1426     l.setArray(expectedArray = newElements);
1427     }
1428     }
1429     }
1430     return removed;
1431     }
1432    
1433 dl 1.100 public Spliterator<E> spliterator() {
1434 dl 1.93 int lo = offset;
1435     int hi = offset + size;
1436     Object[] a = expectedArray;
1437     if (l.getArray() != a)
1438     throw new ConcurrentModificationException();
1439     if (lo < 0 || hi > a.length)
1440     throw new IndexOutOfBoundsException();
1441 dl 1.99 return Spliterators.spliterator
1442 dl 1.98 (a, lo, hi, Spliterator.IMMUTABLE | Spliterator.ORDERED);
1443     }
1444    
1445 tim 1.7 }
1446 tim 1.1
1447 tim 1.7 private static class COWSubListIterator<E> implements ListIterator<E> {
1448 jsr166 1.80 private final ListIterator<E> it;
1449 tim 1.7 private final int offset;
1450     private final int size;
1451 jsr166 1.66
1452 jsr166 1.79 COWSubListIterator(List<E> l, int index, int offset, int size) {
1453 tim 1.7 this.offset = offset;
1454     this.size = size;
1455 jsr166 1.80 it = l.listIterator(index+offset);
1456 tim 1.7 }
1457 tim 1.1
1458 tim 1.7 public boolean hasNext() {
1459     return nextIndex() < size;
1460     }
1461 tim 1.1
1462 tim 1.7 public E next() {
1463     if (hasNext())
1464 jsr166 1.80 return it.next();
1465 tim 1.7 else
1466     throw new NoSuchElementException();
1467     }
1468 tim 1.1
1469 tim 1.7 public boolean hasPrevious() {
1470     return previousIndex() >= 0;
1471     }
1472 tim 1.1
1473 tim 1.7 public E previous() {
1474     if (hasPrevious())
1475 jsr166 1.80 return it.previous();
1476 tim 1.7 else
1477     throw new NoSuchElementException();
1478     }
1479 tim 1.1
1480 tim 1.7 public int nextIndex() {
1481 jsr166 1.80 return it.nextIndex() - offset;
1482 tim 1.7 }
1483 tim 1.1
1484 tim 1.7 public int previousIndex() {
1485 jsr166 1.80 return it.previousIndex() - offset;
1486 tim 1.1 }
1487    
1488 tim 1.7 public void remove() {
1489     throw new UnsupportedOperationException();
1490     }
1491 tim 1.1
1492 jsr166 1.33 public void set(E e) {
1493 tim 1.7 throw new UnsupportedOperationException();
1494 tim 1.1 }
1495    
1496 jsr166 1.33 public void add(E e) {
1497 tim 1.7 throw new UnsupportedOperationException();
1498     }
1499 tim 1.1 }
1500    
1501 dl 1.42 // Support for resetting lock while deserializing
1502 dl 1.72 private void resetLock() {
1503 jsr166 1.124 U.putObjectVolatile(this, LOCK, new Object());
1504 dl 1.72 }
1505 jsr166 1.123 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe();
1506     private static final long LOCK;
1507 dl 1.42 static {
1508     try {
1509 jsr166 1.123 LOCK = U.objectFieldOffset
1510     (CopyOnWriteArrayList.class.getDeclaredField("lock"));
1511 jsr166 1.122 } catch (ReflectiveOperationException e) {
1512 dl 1.72 throw new Error(e);
1513     }
1514 dl 1.42 }
1515 tim 1.1 }