ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.114
Committed: Mon Nov 4 00:00:39 2013 UTC (10 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.113: +1 -1 lines
Log Message:
stop using denigrated: Foo bar[];

File Contents

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