ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.156
Committed: Wed Mar 20 01:21:51 2019 UTC (5 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.155: +2 -1 lines
Log Message:
8221120: CopyOnWriteArrayList.set should always have volatile write semantics

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