ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.122
Committed: Sun Jan 4 01:06:15 2015 UTC (9 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.121: +1 -1 lines
Log Message:
use ReflectiveOperationException for Unsafe mechanics

File Contents

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