ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.102
Committed: Sat Apr 6 17:21:51 2013 UTC (11 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.101: +1 -1 lines
Log Message:
coding style

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