ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.153
Committed: Tue Jun 19 00:00:43 2018 UTC (5 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.152: +3 -1 lines
Log Message:
use release fence only in clone; not needed in readObject

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.144 import jdk.internal.misc.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.143 * <a href="{@docRoot}/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     setArray(es);
399 jsr166 1.67 }
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.148 Object[] es = getArray();
413     int len = es.length;
414     es = Arrays.copyOf(es, len + 1);
415     es[len] = e;
416     setArray(es);
417 jsr166 1.67 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.148 Object[] es = getArray();
431     int len = es.length;
432 jsr166 1.67 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 jsr166 1.148 newElements = Arrays.copyOf(es, len + 1);
438 jsr166 1.67 else {
439     newElements = new Object[len + 1];
440 jsr166 1.148 System.arraycopy(es, 0, newElements, 0, index);
441     System.arraycopy(es, index, newElements, index + 1,
442 jsr166 1.67 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.148 Object[] es = getArray();
459     int len = es.length;
460     E oldValue = elementAt(es, index);
461 jsr166 1.67 int numMoved = len - index - 1;
462 jsr166 1.148 Object[] newElements;
463 jsr166 1.67 if (numMoved == 0)
464 jsr166 1.148 newElements = Arrays.copyOf(es, len - 1);
465 jsr166 1.67 else {
466 jsr166 1.148 newElements = new Object[len - 1];
467     System.arraycopy(es, 0, newElements, 0, index);
468     System.arraycopy(es, index + 1, newElements, index,
469 jsr166 1.67 numMoved);
470     }
471 jsr166 1.148 setArray(newElements);
472 jsr166 1.67 return oldValue;
473     }
474 tim 1.1 }
475    
476     /**
477 jsr166 1.35 * Removes the first occurrence of the specified element from this list,
478     * if it is present. If this list does not contain the element, it is
479     * unchanged. More formally, removes the element with the lowest index
480 jsr166 1.116 * {@code i} such that {@code Objects.equals(o, get(i))}
481 jsr166 1.92 * (if such an element exists). Returns {@code true} if this list
482 jsr166 1.35 * contained the specified element (or equivalently, if this list
483     * changed as a result of the call).
484 tim 1.1 *
485 jsr166 1.35 * @param o element to be removed from this list, if present
486 jsr166 1.92 * @return {@code true} if this list contained the specified element
487 tim 1.1 */
488 dl 1.42 public boolean remove(Object o) {
489 jsr166 1.104 Object[] snapshot = getArray();
490 jsr166 1.148 int index = indexOfRange(o, snapshot, 0, snapshot.length);
491 jsr166 1.146 return index >= 0 && remove(o, snapshot, index);
492 jsr166 1.104 }
493    
494     /**
495     * A version of remove(Object) using the strong hint that given
496     * recent snapshot contains o at the given index.
497     */
498     private boolean remove(Object o, Object[] snapshot, int index) {
499 jsr166 1.124 synchronized (lock) {
500 jsr166 1.104 Object[] current = getArray();
501     int len = current.length;
502     if (snapshot != current) findIndex: {
503     int prefix = Math.min(index, len);
504     for (int i = 0; i < prefix; i++) {
505 jsr166 1.129 if (current[i] != snapshot[i]
506     && Objects.equals(o, current[i])) {
507 jsr166 1.104 index = i;
508     break findIndex;
509     }
510 jsr166 1.67 }
511 jsr166 1.104 if (index >= len)
512     return false;
513     if (current[index] == o)
514     break findIndex;
515 jsr166 1.148 index = indexOfRange(o, current, index, len);
516 jsr166 1.104 if (index < 0)
517     return false;
518 jsr166 1.67 }
519 jsr166 1.104 Object[] newElements = new Object[len - 1];
520     System.arraycopy(current, 0, newElements, 0, index);
521     System.arraycopy(current, index + 1,
522     newElements, index,
523     len - index - 1);
524     setArray(newElements);
525     return true;
526 jsr166 1.67 }
527 tim 1.1 }
528    
529     /**
530 jsr166 1.35 * Removes from this list all of the elements whose index is between
531 jsr166 1.92 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
532 jsr166 1.35 * Shifts any succeeding elements to the left (reduces their index).
533 jsr166 1.92 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
534     * (If {@code toIndex==fromIndex}, this operation has no effect.)
535 tim 1.1 *
536 jsr166 1.35 * @param fromIndex index of first element to be removed
537     * @param toIndex index after last element to be removed
538 jsr166 1.66 * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range
539 jsr166 1.86 * ({@code fromIndex < 0 || toIndex > size() || toIndex < fromIndex})
540 tim 1.1 */
541 jsr166 1.84 void removeRange(int fromIndex, int toIndex) {
542 jsr166 1.124 synchronized (lock) {
543 jsr166 1.148 Object[] es = getArray();
544     int len = es.length;
545 jsr166 1.67
546     if (fromIndex < 0 || toIndex > len || toIndex < fromIndex)
547     throw new IndexOutOfBoundsException();
548     int newlen = len - (toIndex - fromIndex);
549     int numMoved = len - toIndex;
550     if (numMoved == 0)
551 jsr166 1.148 setArray(Arrays.copyOf(es, newlen));
552 jsr166 1.67 else {
553     Object[] newElements = new Object[newlen];
554 jsr166 1.148 System.arraycopy(es, 0, newElements, 0, fromIndex);
555     System.arraycopy(es, toIndex, newElements,
556 jsr166 1.67 fromIndex, numMoved);
557     setArray(newElements);
558     }
559     }
560 tim 1.1 }
561    
562     /**
563 jsr166 1.90 * Appends the element, if not present.
564 jsr166 1.38 *
565 dl 1.40 * @param e element to be added to this list, if absent
566 jsr166 1.92 * @return {@code true} if the element was added
567 jsr166 1.30 */
568 dl 1.42 public boolean addIfAbsent(E e) {
569 jsr166 1.104 Object[] snapshot = getArray();
570 jsr166 1.148 return indexOfRange(e, snapshot, 0, snapshot.length) < 0
571 jsr166 1.146 && addIfAbsent(e, snapshot);
572 jsr166 1.104 }
573    
574     /**
575     * A version of addIfAbsent using the strong hint that given
576     * recent snapshot does not contain e.
577     */
578     private boolean addIfAbsent(E e, Object[] snapshot) {
579 jsr166 1.124 synchronized (lock) {
580 jsr166 1.104 Object[] current = getArray();
581     int len = current.length;
582     if (snapshot != current) {
583     // Optimize for lost race to another addXXX operation
584     int common = Math.min(snapshot.length, len);
585     for (int i = 0; i < common; i++)
586 jsr166 1.129 if (current[i] != snapshot[i]
587     && Objects.equals(e, current[i]))
588 jsr166 1.104 return false;
589 jsr166 1.148 if (indexOfRange(e, current, common, len) >= 0)
590 jsr166 1.104 return false;
591 jsr166 1.67 }
592 jsr166 1.104 Object[] newElements = Arrays.copyOf(current, len + 1);
593 jsr166 1.67 newElements[len] = e;
594     setArray(newElements);
595     return true;
596     }
597 tim 1.1 }
598    
599     /**
600 jsr166 1.92 * Returns {@code true} if this list contains all of the elements of the
601 jsr166 1.32 * specified collection.
602 jsr166 1.34 *
603 jsr166 1.36 * @param c collection to be checked for containment in this list
604 jsr166 1.92 * @return {@code true} if this list contains all of the elements of the
605 jsr166 1.35 * specified collection
606     * @throws NullPointerException if the specified collection is null
607 jsr166 1.38 * @see #contains(Object)
608 tim 1.1 */
609 tim 1.7 public boolean containsAll(Collection<?> c) {
610 jsr166 1.148 Object[] es = getArray();
611     int len = es.length;
612 jsr166 1.67 for (Object e : c) {
613 jsr166 1.148 if (indexOfRange(e, es, 0, len) < 0)
614 tim 1.1 return false;
615 jsr166 1.67 }
616 tim 1.1 return true;
617     }
618    
619     /**
620 jsr166 1.32 * Removes from this list all of its elements that are contained in
621     * the specified collection. This is a particularly expensive operation
622 tim 1.1 * in this class because of the need for an internal temporary array.
623     *
624 jsr166 1.35 * @param c collection containing elements to be removed from this list
625 jsr166 1.92 * @return {@code true} if this list changed as a result of the call
626 jsr166 1.38 * @throws ClassCastException if the class of an element of this list
627 dl 1.73 * is incompatible with the specified collection
628 jsr166 1.134 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>)
629 jsr166 1.38 * @throws NullPointerException if this list contains a null element and the
630 dl 1.73 * specified collection does not permit null elements
631 jsr166 1.134 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>),
632 jsr166 1.38 * or if the specified collection is null
633     * @see #remove(Object)
634 tim 1.1 */
635 dl 1.42 public boolean removeAll(Collection<?> c) {
636 jsr166 1.140 Objects.requireNonNull(c);
637     return bulkRemove(e -> c.contains(e));
638 tim 1.1 }
639    
640     /**
641 jsr166 1.32 * Retains only the elements in this list that are contained in the
642 jsr166 1.35 * specified collection. In other words, removes from this list all of
643     * its elements that are not contained in the specified collection.
644 jsr166 1.32 *
645 jsr166 1.35 * @param c collection containing elements to be retained in this list
646 jsr166 1.92 * @return {@code true} if this list changed as a result of the call
647 jsr166 1.38 * @throws ClassCastException if the class of an element of this list
648 dl 1.73 * is incompatible with the specified collection
649 jsr166 1.134 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>)
650 jsr166 1.38 * @throws NullPointerException if this list contains a null element and the
651 dl 1.73 * specified collection does not permit null elements
652 jsr166 1.134 * (<a href="{@docRoot}/../api/java/util/Collection.html#optional-restrictions">optional</a>),
653 jsr166 1.38 * or if the specified collection is null
654     * @see #remove(Object)
655 tim 1.1 */
656 dl 1.42 public boolean retainAll(Collection<?> c) {
657 jsr166 1.140 Objects.requireNonNull(c);
658     return bulkRemove(e -> !c.contains(e));
659 tim 1.1 }
660    
661     /**
662 jsr166 1.32 * Appends all of the elements in the specified collection that
663 tim 1.1 * are not already contained in this list, to the end of
664     * this list, in the order that they are returned by the
665 jsr166 1.32 * specified collection's iterator.
666 tim 1.1 *
667 jsr166 1.36 * @param c collection containing elements to be added to this list
668 tim 1.1 * @return the number of elements added
669 jsr166 1.35 * @throws NullPointerException if the specified collection is null
670 jsr166 1.38 * @see #addIfAbsent(Object)
671 tim 1.1 */
672 dl 1.42 public int addAllAbsent(Collection<? extends E> c) {
673 jsr166 1.67 Object[] cs = c.toArray();
674     if (cs.length == 0)
675     return 0;
676 jsr166 1.124 synchronized (lock) {
677 jsr166 1.148 Object[] es = getArray();
678     int len = es.length;
679 jsr166 1.67 int added = 0;
680 jsr166 1.103 // uniquify and compact elements in cs
681     for (int i = 0; i < cs.length; ++i) {
682 jsr166 1.67 Object e = cs[i];
683 jsr166 1.148 if (indexOfRange(e, es, 0, len) < 0 &&
684     indexOfRange(e, cs, 0, added) < 0)
685 jsr166 1.103 cs[added++] = e;
686 jsr166 1.67 }
687     if (added > 0) {
688 jsr166 1.148 Object[] newElements = Arrays.copyOf(es, len + added);
689 jsr166 1.103 System.arraycopy(cs, 0, newElements, len, added);
690 jsr166 1.67 setArray(newElements);
691     }
692     return added;
693     }
694 tim 1.1 }
695    
696     /**
697     * Removes all of the elements from this list.
698 jsr166 1.38 * The list will be empty after this call returns.
699 tim 1.1 */
700 dl 1.42 public void clear() {
701 jsr166 1.124 synchronized (lock) {
702 jsr166 1.67 setArray(new Object[0]);
703     }
704 tim 1.1 }
705    
706     /**
707 jsr166 1.32 * Appends all of the elements in the specified collection to the end
708     * of this list, in the order that they are returned by the specified
709     * collection's iterator.
710 tim 1.1 *
711 jsr166 1.36 * @param c collection containing elements to be added to this list
712 jsr166 1.92 * @return {@code true} if this list changed as a result of the call
713 jsr166 1.35 * @throws NullPointerException if the specified collection is null
714 jsr166 1.38 * @see #add(Object)
715 tim 1.1 */
716 dl 1.42 public boolean addAll(Collection<? extends E> c) {
717 dl 1.106 Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
718     ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
719 jsr166 1.67 if (cs.length == 0)
720     return false;
721 jsr166 1.124 synchronized (lock) {
722 jsr166 1.148 Object[] es = getArray();
723     int len = es.length;
724     Object[] newElements;
725 dl 1.106 if (len == 0 && cs.getClass() == Object[].class)
726 jsr166 1.148 newElements = cs;
727 dl 1.106 else {
728 jsr166 1.148 newElements = Arrays.copyOf(es, len + cs.length);
729 dl 1.106 System.arraycopy(cs, 0, newElements, len, cs.length);
730     }
731 jsr166 1.148 setArray(newElements);
732 jsr166 1.67 return true;
733     }
734 tim 1.1 }
735    
736     /**
737 jsr166 1.35 * Inserts all of the elements in the specified collection into this
738 tim 1.1 * list, starting at the specified position. Shifts the element
739     * currently at that position (if any) and any subsequent elements to
740     * the right (increases their indices). The new elements will appear
741 jsr166 1.38 * in this list in the order that they are returned by the
742     * specified collection's iterator.
743 tim 1.1 *
744 jsr166 1.35 * @param index index at which to insert the first element
745     * from the specified collection
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 IndexOutOfBoundsException {@inheritDoc}
749     * @throws NullPointerException if the specified collection is null
750 jsr166 1.38 * @see #add(int,Object)
751 tim 1.1 */
752 dl 1.42 public boolean addAll(int index, Collection<? extends E> c) {
753 jsr166 1.67 Object[] cs = c.toArray();
754 jsr166 1.124 synchronized (lock) {
755 jsr166 1.148 Object[] es = getArray();
756     int len = es.length;
757 jsr166 1.67 if (index > len || index < 0)
758 jsr166 1.125 throw new IndexOutOfBoundsException(outOfBounds(index, len));
759 jsr166 1.67 if (cs.length == 0)
760     return false;
761     int numMoved = len - index;
762     Object[] newElements;
763     if (numMoved == 0)
764 jsr166 1.148 newElements = Arrays.copyOf(es, len + cs.length);
765 jsr166 1.67 else {
766     newElements = new Object[len + cs.length];
767 jsr166 1.148 System.arraycopy(es, 0, newElements, 0, index);
768     System.arraycopy(es, index,
769 jsr166 1.67 newElements, index + cs.length,
770     numMoved);
771     }
772     System.arraycopy(cs, 0, newElements, index, cs.length);
773     setArray(newElements);
774     return true;
775     }
776 tim 1.1 }
777    
778 jsr166 1.141 /**
779     * @throws NullPointerException {@inheritDoc}
780     */
781 dl 1.106 public void forEach(Consumer<? super E> action) {
782 jsr166 1.142 Objects.requireNonNull(action);
783 jsr166 1.126 for (Object x : getArray()) {
784     @SuppressWarnings("unchecked") E e = (E) x;
785 dl 1.106 action.accept(e);
786     }
787     }
788    
789 jsr166 1.141 /**
790     * @throws NullPointerException {@inheritDoc}
791     */
792 dl 1.106 public boolean removeIf(Predicate<? super E> filter) {
793 jsr166 1.142 Objects.requireNonNull(filter);
794 jsr166 1.140 return bulkRemove(filter);
795     }
796    
797     // A tiny bit set implementation
798    
799     private static long[] nBits(int n) {
800     return new long[((n - 1) >> 6) + 1];
801     }
802     private static void setBit(long[] bits, int i) {
803     bits[i >> 6] |= 1L << i;
804     }
805     private static boolean isClear(long[] bits, int i) {
806     return (bits[i >> 6] & (1L << i)) == 0;
807     }
808    
809     private boolean bulkRemove(Predicate<? super E> filter) {
810 jsr166 1.124 synchronized (lock) {
811 jsr166 1.140 return bulkRemove(filter, 0, getArray().length);
812     }
813     }
814    
815     boolean bulkRemove(Predicate<? super E> filter, int i, int end) {
816     // assert Thread.holdsLock(lock);
817     final Object[] es = getArray();
818     // Optimize for initial run of survivors
819     for (; i < end && !filter.test(elementAt(es, i)); i++)
820     ;
821     if (i < end) {
822     final int beg = i;
823     final long[] deathRow = nBits(end - beg);
824     int deleted = 1;
825     deathRow[0] = 1L; // set bit 0
826     for (i = beg + 1; i < end; i++)
827     if (filter.test(elementAt(es, i))) {
828     setBit(deathRow, i - beg);
829     deleted++;
830 dl 1.106 }
831 jsr166 1.140 // Did filter reentrantly modify the list?
832     if (es != getArray())
833     throw new ConcurrentModificationException();
834     final Object[] newElts = Arrays.copyOf(es, es.length - deleted);
835     int w = beg;
836     for (i = beg; i < end; i++)
837     if (isClear(deathRow, i - beg))
838     newElts[w++] = es[i];
839     System.arraycopy(es, i, newElts, w, es.length - i);
840     setArray(newElts);
841     return true;
842     } else {
843     if (es != getArray())
844     throw new ConcurrentModificationException();
845     return false;
846 dl 1.106 }
847     }
848    
849     public void replaceAll(UnaryOperator<E> operator) {
850 jsr166 1.124 synchronized (lock) {
851 jsr166 1.148 replaceAllRange(operator, 0, getArray().length);
852 dl 1.106 }
853     }
854    
855 jsr166 1.148 void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
856 jsr166 1.140 // assert Thread.holdsLock(lock);
857 jsr166 1.150 Objects.requireNonNull(operator);
858 jsr166 1.140 final Object[] es = getArray().clone();
859     for (; i < end; i++)
860     es[i] = operator.apply(elementAt(es, i));
861     setArray(es);
862     }
863    
864 dl 1.106 public void sort(Comparator<? super E> c) {
865 jsr166 1.124 synchronized (lock) {
866 jsr166 1.148 sortRange(c, 0, getArray().length);
867 dl 1.106 }
868     }
869    
870 jsr166 1.140 @SuppressWarnings("unchecked")
871 jsr166 1.148 void sortRange(Comparator<? super E> c, int i, int end) {
872 jsr166 1.140 // assert Thread.holdsLock(lock);
873     final Object[] es = getArray().clone();
874     Arrays.sort(es, i, end, (Comparator<Object>)c);
875     setArray(es);
876     }
877    
878 tim 1.1 /**
879 jsr166 1.87 * Saves this list to a stream (that is, serializes it).
880 tim 1.1 *
881 jsr166 1.111 * @param s the stream
882 jsr166 1.112 * @throws java.io.IOException if an I/O error occurs
883 tim 1.1 * @serialData The length of the array backing the list is emitted
884     * (int), followed by all of its elements (each an Object)
885     * in the proper order.
886     */
887     private void writeObject(java.io.ObjectOutputStream s)
888 jsr166 1.85 throws java.io.IOException {
889 tim 1.1
890     s.defaultWriteObject();
891    
892 jsr166 1.148 Object[] es = getArray();
893 tim 1.1 // Write out array length
894 jsr166 1.148 s.writeInt(es.length);
895 tim 1.1
896     // Write out all elements in the proper order.
897 jsr166 1.148 for (Object element : es)
898 jsr166 1.71 s.writeObject(element);
899 tim 1.1 }
900    
901     /**
902 jsr166 1.87 * Reconstitutes this list from a stream (that is, deserializes it).
903 jsr166 1.111 * @param s the stream
904 jsr166 1.112 * @throws ClassNotFoundException if the class of a serialized object
905     * could not be found
906     * @throws java.io.IOException if an I/O error occurs
907 tim 1.1 */
908 dl 1.12 private void readObject(java.io.ObjectInputStream s)
909 tim 1.1 throws java.io.IOException, ClassNotFoundException {
910    
911     s.defaultReadObject();
912    
913 dl 1.42 // bind to new lock
914     resetLock();
915    
916 tim 1.1 // Read in array length and allocate array
917 dl 1.40 int len = s.readInt();
918 jsr166 1.144 SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, len);
919 jsr166 1.148 Object[] es = new Object[len];
920 tim 1.1
921     // Read in all elements in the proper order.
922 dl 1.40 for (int i = 0; i < len; i++)
923 jsr166 1.148 es[i] = s.readObject();
924     setArray(es);
925 tim 1.1 }
926    
927     /**
928 jsr166 1.55 * Returns a string representation of this list. The string
929     * representation consists of the string representations of the list's
930     * elements in the order they are returned by its iterator, enclosed in
931 jsr166 1.92 * square brackets ({@code "[]"}). Adjacent elements are separated by
932     * the characters {@code ", "} (comma and space). Elements are
933 jsr166 1.55 * converted to strings as by {@link String#valueOf(Object)}.
934     *
935     * @return a string representation of this list
936 tim 1.1 */
937     public String toString() {
938 jsr166 1.67 return Arrays.toString(getArray());
939 tim 1.1 }
940    
941     /**
942 jsr166 1.35 * Compares the specified object with this list for equality.
943 jsr166 1.60 * Returns {@code true} if the specified object is the same object
944     * as this object, or if it is also a {@link List} and the sequence
945     * of elements returned by an {@linkplain List#iterator() iterator}
946     * over the specified list is the same as the sequence returned by
947     * an iterator over this list. The two sequences are considered to
948     * be the same if they have the same length and corresponding
949     * elements at the same position in the sequence are <em>equal</em>.
950     * Two elements {@code e1} and {@code e2} are considered
951 jsr166 1.117 * <em>equal</em> if {@code Objects.equals(e1, e2)}.
952 tim 1.1 *
953 jsr166 1.35 * @param o the object to be compared for equality with this list
954 jsr166 1.60 * @return {@code true} if the specified object is equal to this list
955 tim 1.1 */
956     public boolean equals(Object o) {
957     if (o == this)
958     return true;
959     if (!(o instanceof List))
960     return false;
961    
962 jsr166 1.121 List<?> list = (List<?>)o;
963 jsr166 1.67 Iterator<?> it = list.iterator();
964 jsr166 1.147 for (Object element : getArray())
965     if (!it.hasNext() || !Objects.equals(element, it.next()))
966 dl 1.57 return false;
967 jsr166 1.145 return !it.hasNext();
968 tim 1.1 }
969    
970 jsr166 1.148 private static int hashCodeOfRange(Object[] es, int from, int to) {
971     int hashCode = 1;
972     for (int i = from; i < to; i++) {
973     Object x = es[i];
974     hashCode = 31 * hashCode + (x == null ? 0 : x.hashCode());
975     }
976     return hashCode;
977     }
978    
979 tim 1.1 /**
980 jsr166 1.35 * Returns the hash code value for this list.
981 dl 1.26 *
982 jsr166 1.47 * <p>This implementation uses the definition in {@link List#hashCode}.
983     *
984     * @return the hash code value for this list
985 tim 1.1 */
986     public int hashCode() {
987 jsr166 1.148 Object[] es = getArray();
988     return hashCodeOfRange(es, 0, es.length);
989 tim 1.1 }
990    
991     /**
992 jsr166 1.35 * Returns an iterator over the elements in this list in proper sequence.
993     *
994     * <p>The returned iterator provides a snapshot of the state of the list
995     * when the iterator was constructed. No synchronization is needed while
996     * traversing the iterator. The iterator does <em>NOT</em> support the
997 jsr166 1.92 * {@code remove} method.
998 jsr166 1.35 *
999     * @return an iterator over the elements in this list in proper sequence
1000 tim 1.1 */
1001     public Iterator<E> iterator() {
1002 dl 1.40 return new COWIterator<E>(getArray(), 0);
1003 tim 1.1 }
1004    
1005     /**
1006 jsr166 1.35 * {@inheritDoc}
1007 tim 1.1 *
1008 jsr166 1.35 * <p>The returned iterator provides a snapshot of the state of the list
1009     * when the iterator was constructed. No synchronization is needed while
1010     * traversing the iterator. The iterator does <em>NOT</em> support the
1011 jsr166 1.92 * {@code remove}, {@code set} or {@code add} methods.
1012 tim 1.1 */
1013     public ListIterator<E> listIterator() {
1014 dl 1.40 return new COWIterator<E>(getArray(), 0);
1015 tim 1.1 }
1016    
1017     /**
1018 jsr166 1.35 * {@inheritDoc}
1019     *
1020 jsr166 1.50 * <p>The returned iterator provides a snapshot of the state of the list
1021     * when the iterator was constructed. No synchronization is needed while
1022     * traversing the iterator. The iterator does <em>NOT</em> support the
1023 jsr166 1.92 * {@code remove}, {@code set} or {@code add} methods.
1024 jsr166 1.35 *
1025     * @throws IndexOutOfBoundsException {@inheritDoc}
1026 tim 1.1 */
1027 jsr166 1.110 public ListIterator<E> listIterator(int index) {
1028 jsr166 1.148 Object[] es = getArray();
1029     int len = es.length;
1030 jsr166 1.109 if (index < 0 || index > len)
1031 jsr166 1.125 throw new IndexOutOfBoundsException(outOfBounds(index, len));
1032 tim 1.1
1033 jsr166 1.148 return new COWIterator<E>(es, index);
1034 tim 1.1 }
1035    
1036 jsr166 1.113 /**
1037     * Returns a {@link Spliterator} over the elements in this list.
1038     *
1039     * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
1040     * {@link Spliterator#ORDERED}, {@link Spliterator#SIZED}, and
1041     * {@link Spliterator#SUBSIZED}.
1042     *
1043     * <p>The spliterator provides a snapshot of the state of the list
1044     * when the spliterator was constructed. No synchronization is needed while
1045 jsr166 1.135 * operating on the spliterator.
1046 jsr166 1.113 *
1047     * @return a {@code Spliterator} over the elements in this list
1048     * @since 1.8
1049     */
1050 dl 1.100 public Spliterator<E> spliterator() {
1051 dl 1.99 return Spliterators.spliterator
1052 dl 1.98 (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED);
1053     }
1054    
1055 dl 1.93 static final class COWIterator<E> implements ListIterator<E> {
1056 jsr166 1.68 /** Snapshot of the array */
1057 dl 1.41 private final Object[] snapshot;
1058 dl 1.40 /** Index of element to be returned by subsequent call to next. */
1059 tim 1.1 private int cursor;
1060    
1061 jsr166 1.148 COWIterator(Object[] es, int initialCursor) {
1062 tim 1.1 cursor = initialCursor;
1063 jsr166 1.148 snapshot = es;
1064 tim 1.1 }
1065    
1066     public boolean hasNext() {
1067 dl 1.40 return cursor < snapshot.length;
1068 tim 1.1 }
1069    
1070     public boolean hasPrevious() {
1071     return cursor > 0;
1072     }
1073    
1074 jsr166 1.67 @SuppressWarnings("unchecked")
1075 tim 1.1 public E next() {
1076 jsr166 1.67 if (! hasNext())
1077 tim 1.1 throw new NoSuchElementException();
1078 jsr166 1.67 return (E) snapshot[cursor++];
1079 tim 1.1 }
1080    
1081 jsr166 1.67 @SuppressWarnings("unchecked")
1082 tim 1.1 public E previous() {
1083 jsr166 1.67 if (! hasPrevious())
1084 tim 1.1 throw new NoSuchElementException();
1085 jsr166 1.67 return (E) snapshot[--cursor];
1086 tim 1.1 }
1087    
1088     public int nextIndex() {
1089     return cursor;
1090     }
1091    
1092     public int previousIndex() {
1093 jsr166 1.148 return cursor - 1;
1094 tim 1.1 }
1095    
1096     /**
1097     * Not supported. Always throws UnsupportedOperationException.
1098 jsr166 1.92 * @throws UnsupportedOperationException always; {@code remove}
1099 jsr166 1.32 * is not supported by this iterator.
1100 tim 1.1 */
1101     public void remove() {
1102     throw new UnsupportedOperationException();
1103     }
1104    
1105     /**
1106     * Not supported. Always throws UnsupportedOperationException.
1107 jsr166 1.92 * @throws UnsupportedOperationException always; {@code set}
1108 jsr166 1.32 * is not supported by this iterator.
1109 tim 1.1 */
1110 jsr166 1.33 public void set(E e) {
1111 tim 1.1 throw new UnsupportedOperationException();
1112     }
1113    
1114     /**
1115     * Not supported. Always throws UnsupportedOperationException.
1116 jsr166 1.92 * @throws UnsupportedOperationException always; {@code add}
1117 jsr166 1.32 * is not supported by this iterator.
1118 tim 1.1 */
1119 jsr166 1.33 public void add(E e) {
1120 tim 1.1 throw new UnsupportedOperationException();
1121     }
1122 jsr166 1.133
1123     @Override
1124     public void forEachRemaining(Consumer<? super E> action) {
1125     Objects.requireNonNull(action);
1126     final int size = snapshot.length;
1127 jsr166 1.148 int i = cursor;
1128 jsr166 1.133 cursor = size;
1129 jsr166 1.148 for (; i < size; i++)
1130     action.accept(elementAt(snapshot, i));
1131 jsr166 1.133 }
1132 tim 1.1 }
1133    
1134     /**
1135 dl 1.40 * Returns a view of the portion of this list between
1136 jsr166 1.92 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1137 dl 1.40 * The returned list is backed by this list, so changes in the
1138 jsr166 1.66 * returned list are reflected in this list.
1139 dl 1.40 *
1140     * <p>The semantics of the list returned by this method become
1141 jsr166 1.66 * undefined if the backing list (i.e., this list) is modified in
1142     * any way other than via the returned list.
1143 tim 1.1 *
1144 jsr166 1.35 * @param fromIndex low endpoint (inclusive) of the subList
1145     * @param toIndex high endpoint (exclusive) of the subList
1146     * @return a view of the specified range within this list
1147     * @throws IndexOutOfBoundsException {@inheritDoc}
1148 tim 1.1 */
1149 dl 1.42 public List<E> subList(int fromIndex, int toIndex) {
1150 jsr166 1.124 synchronized (lock) {
1151 jsr166 1.148 Object[] es = getArray();
1152     int len = es.length;
1153     int size = toIndex - fromIndex;
1154     if (fromIndex < 0 || toIndex > len || size < 0)
1155 jsr166 1.67 throw new IndexOutOfBoundsException();
1156 jsr166 1.148 return new COWSubList(es, fromIndex, size);
1157 jsr166 1.67 }
1158 tim 1.1 }
1159    
1160 dl 1.42 /**
1161     * Sublist for CopyOnWriteArrayList.
1162     */
1163 jsr166 1.148 private class COWSubList implements List<E>, RandomAccess {
1164 tim 1.1 private final int offset;
1165     private int size;
1166 dl 1.41 private Object[] expectedArray;
1167 tim 1.1
1168 jsr166 1.148 COWSubList(Object[] es, int offset, int size) {
1169     // assert Thread.holdsLock(lock);
1170     expectedArray = es;
1171     this.offset = offset;
1172     this.size = size;
1173 tim 1.1 }
1174    
1175     private void checkForComodification() {
1176 jsr166 1.148 // assert Thread.holdsLock(lock);
1177     if (getArray() != expectedArray)
1178 tim 1.1 throw new ConcurrentModificationException();
1179     }
1180    
1181 jsr166 1.140 private Object[] getArrayChecked() {
1182 jsr166 1.148 // assert Thread.holdsLock(lock);
1183     Object[] a = getArray();
1184 jsr166 1.140 if (a != expectedArray)
1185     throw new ConcurrentModificationException();
1186     return a;
1187     }
1188    
1189 tim 1.1 private void rangeCheck(int index) {
1190 jsr166 1.148 // assert Thread.holdsLock(lock);
1191 jsr166 1.109 if (index < 0 || index >= size)
1192 jsr166 1.125 throw new IndexOutOfBoundsException(outOfBounds(index, size));
1193 tim 1.1 }
1194    
1195 jsr166 1.149 private void rangeCheckForAdd(int index) {
1196     // assert Thread.holdsLock(lock);
1197     if (index < 0 || index > size)
1198     throw new IndexOutOfBoundsException(outOfBounds(index, size));
1199     }
1200    
1201 jsr166 1.148 public Object[] toArray() {
1202     final Object[] es;
1203     final int offset;
1204     final int size;
1205     synchronized (lock) {
1206     es = getArrayChecked();
1207     offset = this.offset;
1208     size = this.size;
1209     }
1210     return Arrays.copyOfRange(es, offset, offset + size);
1211     }
1212    
1213     @SuppressWarnings("unchecked")
1214     public <T> T[] toArray(T[] a) {
1215     final Object[] es;
1216     final int offset;
1217     final int size;
1218     synchronized (lock) {
1219     es = getArrayChecked();
1220     offset = this.offset;
1221     size = this.size;
1222     }
1223     if (a.length < size)
1224     return (T[]) Arrays.copyOfRange(
1225     es, offset, offset + size, a.getClass());
1226     else {
1227     System.arraycopy(es, offset, a, 0, size);
1228     if (a.length > size)
1229     a[size] = null;
1230     return a;
1231     }
1232     }
1233    
1234     public int indexOf(Object o) {
1235     final Object[] es;
1236     final int offset;
1237     final int size;
1238     synchronized (lock) {
1239     es = getArrayChecked();
1240     offset = this.offset;
1241     size = this.size;
1242     }
1243     int i = indexOfRange(o, es, offset, offset + size);
1244     return (i == -1) ? -1 : i - offset;
1245     }
1246    
1247     public int lastIndexOf(Object o) {
1248     final Object[] es;
1249     final int offset;
1250     final int size;
1251     synchronized (lock) {
1252     es = getArrayChecked();
1253     offset = this.offset;
1254     size = this.size;
1255     }
1256     int i = lastIndexOfRange(o, es, offset, offset + size);
1257     return (i == -1) ? -1 : i - offset;
1258     }
1259    
1260     public boolean contains(Object o) {
1261     return indexOf(o) >= 0;
1262     }
1263    
1264     public boolean containsAll(Collection<?> c) {
1265     final Object[] es;
1266     final int offset;
1267     final int size;
1268     synchronized (lock) {
1269     es = getArrayChecked();
1270     offset = this.offset;
1271     size = this.size;
1272     }
1273     for (Object o : c)
1274     if (indexOfRange(o, es, offset, offset + size) < 0)
1275     return false;
1276     return true;
1277     }
1278    
1279     public boolean isEmpty() {
1280     return size() == 0;
1281     }
1282    
1283     public String toString() {
1284     return Arrays.toString(toArray());
1285     }
1286    
1287     public int hashCode() {
1288     final Object[] es;
1289     final int offset;
1290     final int size;
1291     synchronized (lock) {
1292     es = getArrayChecked();
1293     offset = this.offset;
1294     size = this.size;
1295     }
1296     return hashCodeOfRange(es, offset, offset + size);
1297     }
1298    
1299     public boolean equals(Object o) {
1300     if (o == this)
1301     return true;
1302     if (!(o instanceof List))
1303     return false;
1304 jsr166 1.151 Iterator<?> it = ((List<?>)o).iterator();
1305 jsr166 1.148
1306     final Object[] es;
1307     final int offset;
1308     final int size;
1309     synchronized (lock) {
1310     es = getArrayChecked();
1311     offset = this.offset;
1312     size = this.size;
1313     }
1314    
1315     for (int i = offset, end = offset + size; i < end; i++)
1316     if (!it.hasNext() || !Objects.equals(es[i], it.next()))
1317     return false;
1318     return !it.hasNext();
1319     }
1320    
1321 tim 1.1 public E set(int index, E element) {
1322 jsr166 1.148 synchronized (lock) {
1323 tim 1.1 rangeCheck(index);
1324     checkForComodification();
1325 jsr166 1.148 E x = CopyOnWriteArrayList.this.set(offset + index, element);
1326     expectedArray = getArray();
1327 tim 1.1 return x;
1328 jsr166 1.67 }
1329 tim 1.1 }
1330    
1331     public E get(int index) {
1332 jsr166 1.148 synchronized (lock) {
1333 tim 1.1 rangeCheck(index);
1334     checkForComodification();
1335 jsr166 1.148 return CopyOnWriteArrayList.this.get(offset + index);
1336 jsr166 1.67 }
1337 tim 1.1 }
1338    
1339     public int size() {
1340 jsr166 1.148 synchronized (lock) {
1341 tim 1.1 checkForComodification();
1342     return size;
1343 jsr166 1.67 }
1344 tim 1.1 }
1345    
1346 jsr166 1.140 public boolean add(E element) {
1347 jsr166 1.148 synchronized (lock) {
1348 jsr166 1.140 checkForComodification();
1349 jsr166 1.148 CopyOnWriteArrayList.this.add(offset + size, element);
1350     expectedArray = getArray();
1351 jsr166 1.140 size++;
1352     }
1353     return true;
1354     }
1355    
1356 tim 1.1 public void add(int index, E element) {
1357 jsr166 1.148 synchronized (lock) {
1358 tim 1.1 checkForComodification();
1359 jsr166 1.149 rangeCheckForAdd(index);
1360 jsr166 1.148 CopyOnWriteArrayList.this.add(offset + index, element);
1361     expectedArray = getArray();
1362 tim 1.1 size++;
1363 jsr166 1.67 }
1364 tim 1.1 }
1365    
1366 jsr166 1.140 public boolean addAll(Collection<? extends E> c) {
1367 jsr166 1.148 synchronized (lock) {
1368 jsr166 1.140 final Object[] oldArray = getArrayChecked();
1369 jsr166 1.148 boolean modified =
1370     CopyOnWriteArrayList.this.addAll(offset + size, c);
1371     size += (expectedArray = getArray()).length - oldArray.length;
1372     return modified;
1373     }
1374     }
1375    
1376     public boolean addAll(int index, Collection<? extends E> c) {
1377     synchronized (lock) {
1378 jsr166 1.149 rangeCheckForAdd(index);
1379 jsr166 1.148 final Object[] oldArray = getArrayChecked();
1380     boolean modified =
1381     CopyOnWriteArrayList.this.addAll(offset + index, c);
1382     size += (expectedArray = getArray()).length - oldArray.length;
1383 jsr166 1.140 return modified;
1384     }
1385     }
1386    
1387 dl 1.13 public void clear() {
1388 jsr166 1.148 synchronized (lock) {
1389 dl 1.13 checkForComodification();
1390 jsr166 1.148 removeRange(offset, offset + size);
1391     expectedArray = getArray();
1392 dl 1.13 size = 0;
1393 jsr166 1.67 }
1394 dl 1.13 }
1395    
1396 tim 1.1 public E remove(int index) {
1397 jsr166 1.148 synchronized (lock) {
1398 tim 1.1 rangeCheck(index);
1399     checkForComodification();
1400 jsr166 1.148 E result = CopyOnWriteArrayList.this.remove(offset + index);
1401     expectedArray = getArray();
1402 tim 1.1 size--;
1403     return result;
1404 jsr166 1.67 }
1405 tim 1.1 }
1406    
1407 jsr166 1.66 public boolean remove(Object o) {
1408 jsr166 1.148 synchronized (lock) {
1409 jsr166 1.140 checkForComodification();
1410     int index = indexOf(o);
1411     if (index == -1)
1412     return false;
1413     remove(index);
1414     return true;
1415     }
1416 jsr166 1.66 }
1417    
1418 tim 1.1 public Iterator<E> iterator() {
1419 jsr166 1.148 return listIterator(0);
1420     }
1421    
1422     public ListIterator<E> listIterator() {
1423     return listIterator(0);
1424 tim 1.1 }
1425    
1426 jsr166 1.110 public ListIterator<E> listIterator(int index) {
1427 jsr166 1.148 synchronized (lock) {
1428 tim 1.1 checkForComodification();
1429 jsr166 1.149 rangeCheckForAdd(index);
1430 jsr166 1.148 return new COWSubListIterator<E>(
1431     CopyOnWriteArrayList.this, index, offset, size);
1432 jsr166 1.67 }
1433 tim 1.1 }
1434    
1435 tim 1.7 public List<E> subList(int fromIndex, int toIndex) {
1436 jsr166 1.148 synchronized (lock) {
1437 tim 1.7 checkForComodification();
1438 jsr166 1.115 if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
1439 tim 1.7 throw new IndexOutOfBoundsException();
1440 jsr166 1.148 return new COWSubList(expectedArray, fromIndex + offset, toIndex - fromIndex);
1441 jsr166 1.67 }
1442 tim 1.7 }
1443 tim 1.1
1444 dl 1.106 public void forEach(Consumer<? super E> action) {
1445 jsr166 1.142 Objects.requireNonNull(action);
1446 jsr166 1.140 int i, end; final Object[] es;
1447 jsr166 1.148 synchronized (lock) {
1448 jsr166 1.140 es = getArrayChecked();
1449     i = offset;
1450     end = i + size;
1451 dl 1.106 }
1452 jsr166 1.140 for (; i < end; i++)
1453     action.accept(elementAt(es, i));
1454 dl 1.106 }
1455    
1456 dl 1.108 public void replaceAll(UnaryOperator<E> operator) {
1457 jsr166 1.148 synchronized (lock) {
1458 jsr166 1.140 checkForComodification();
1459 jsr166 1.148 replaceAllRange(operator, offset, offset + size);
1460     expectedArray = getArray();
1461 dl 1.108 }
1462     }
1463    
1464     public void sort(Comparator<? super E> c) {
1465 jsr166 1.148 synchronized (lock) {
1466 jsr166 1.140 checkForComodification();
1467 jsr166 1.148 sortRange(c, offset, offset + size);
1468     expectedArray = getArray();
1469 dl 1.108 }
1470     }
1471    
1472     public boolean removeAll(Collection<?> c) {
1473 jsr166 1.140 Objects.requireNonNull(c);
1474     return bulkRemove(e -> c.contains(e));
1475 dl 1.108 }
1476    
1477     public boolean retainAll(Collection<?> c) {
1478 jsr166 1.140 Objects.requireNonNull(c);
1479     return bulkRemove(e -> !c.contains(e));
1480 dl 1.108 }
1481    
1482     public boolean removeIf(Predicate<? super E> filter) {
1483 jsr166 1.140 Objects.requireNonNull(filter);
1484     return bulkRemove(filter);
1485     }
1486    
1487     private boolean bulkRemove(Predicate<? super E> filter) {
1488 jsr166 1.148 synchronized (lock) {
1489 jsr166 1.140 final Object[] oldArray = getArrayChecked();
1490 jsr166 1.148 boolean modified = CopyOnWriteArrayList.this.bulkRemove(
1491     filter, offset, offset + size);
1492     size += (expectedArray = getArray()).length - oldArray.length;
1493 jsr166 1.140 return modified;
1494 dl 1.108 }
1495     }
1496    
1497 dl 1.100 public Spliterator<E> spliterator() {
1498 jsr166 1.148 synchronized (lock) {
1499 jsr166 1.140 return Spliterators.spliterator(
1500     getArrayChecked(), offset, offset + size,
1501     Spliterator.IMMUTABLE | Spliterator.ORDERED);
1502     }
1503 dl 1.98 }
1504    
1505 tim 1.7 }
1506 tim 1.1
1507 tim 1.7 private static class COWSubListIterator<E> implements ListIterator<E> {
1508 jsr166 1.80 private final ListIterator<E> it;
1509 tim 1.7 private final int offset;
1510     private final int size;
1511 jsr166 1.66
1512 jsr166 1.79 COWSubListIterator(List<E> l, int index, int offset, int size) {
1513 tim 1.7 this.offset = offset;
1514     this.size = size;
1515 jsr166 1.148 it = l.listIterator(index + offset);
1516 tim 1.7 }
1517 tim 1.1
1518 tim 1.7 public boolean hasNext() {
1519     return nextIndex() < size;
1520     }
1521 tim 1.1
1522 tim 1.7 public E next() {
1523     if (hasNext())
1524 jsr166 1.80 return it.next();
1525 tim 1.7 else
1526     throw new NoSuchElementException();
1527     }
1528 tim 1.1
1529 tim 1.7 public boolean hasPrevious() {
1530     return previousIndex() >= 0;
1531     }
1532 tim 1.1
1533 tim 1.7 public E previous() {
1534     if (hasPrevious())
1535 jsr166 1.80 return it.previous();
1536 tim 1.7 else
1537     throw new NoSuchElementException();
1538     }
1539 tim 1.1
1540 tim 1.7 public int nextIndex() {
1541 jsr166 1.80 return it.nextIndex() - offset;
1542 tim 1.7 }
1543 tim 1.1
1544 tim 1.7 public int previousIndex() {
1545 jsr166 1.80 return it.previousIndex() - offset;
1546 tim 1.1 }
1547    
1548 tim 1.7 public void remove() {
1549     throw new UnsupportedOperationException();
1550     }
1551 tim 1.1
1552 jsr166 1.33 public void set(E e) {
1553 tim 1.7 throw new UnsupportedOperationException();
1554 tim 1.1 }
1555    
1556 jsr166 1.33 public void add(E e) {
1557 tim 1.7 throw new UnsupportedOperationException();
1558     }
1559 jsr166 1.133
1560     @Override
1561     @SuppressWarnings("unchecked")
1562     public void forEachRemaining(Consumer<? super E> action) {
1563     Objects.requireNonNull(action);
1564 jsr166 1.148 while (hasNext()) {
1565 jsr166 1.133 action.accept(it.next());
1566     }
1567     }
1568 tim 1.1 }
1569    
1570 jsr166 1.139 /** Initializes the lock; for use when deserializing or cloning. */
1571 dl 1.72 private void resetLock() {
1572 jsr166 1.138 Field lockField = java.security.AccessController.doPrivileged(
1573     (java.security.PrivilegedAction<Field>) () -> {
1574     try {
1575     Field f = CopyOnWriteArrayList.class
1576     .getDeclaredField("lock");
1577     f.setAccessible(true);
1578     return f;
1579     } catch (ReflectiveOperationException e) {
1580     throw new Error(e);
1581     }});
1582 dl 1.42 try {
1583 jsr166 1.138 lockField.set(this, new Object());
1584     } catch (IllegalAccessException e) {
1585 dl 1.72 throw new Error(e);
1586     }
1587 dl 1.42 }
1588 tim 1.1 }