ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.152
Committed: Mon Jun 18 20:01:07 2018 UTC (5 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.151: +2 -0 lines
Log Message:
resetLock: add a release fence

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