ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.111
Committed: Thu Jul 18 17:38:29 2013 UTC (10 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.110: +2 -0 lines
Log Message:
javadoc warning fixes: add serialization method @param

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 * @serialData The length of the array backing the list is emitted
939 * (int), followed by all of its elements (each an Object)
940 * in the proper order.
941 */
942 private void writeObject(java.io.ObjectOutputStream s)
943 throws java.io.IOException {
944
945 s.defaultWriteObject();
946
947 Object[] elements = getArray();
948 // Write out array length
949 s.writeInt(elements.length);
950
951 // Write out all elements in the proper order.
952 for (Object element : elements)
953 s.writeObject(element);
954 }
955
956 /**
957 * Reconstitutes this list from a stream (that is, deserializes it).
958 * @param s the stream
959 */
960 private void readObject(java.io.ObjectInputStream s)
961 throws java.io.IOException, ClassNotFoundException {
962
963 s.defaultReadObject();
964
965 // bind to new lock
966 resetLock();
967
968 // Read in array length and allocate array
969 int len = s.readInt();
970 Object[] elements = new Object[len];
971
972 // Read in all elements in the proper order.
973 for (int i = 0; i < len; i++)
974 elements[i] = s.readObject();
975 setArray(elements);
976 }
977
978 /**
979 * Returns a string representation of this list. The string
980 * representation consists of the string representations of the list's
981 * elements in the order they are returned by its iterator, enclosed in
982 * square brackets ({@code "[]"}). Adjacent elements are separated by
983 * the characters {@code ", "} (comma and space). Elements are
984 * converted to strings as by {@link String#valueOf(Object)}.
985 *
986 * @return a string representation of this list
987 */
988 public String toString() {
989 return Arrays.toString(getArray());
990 }
991
992 /**
993 * Compares the specified object with this list for equality.
994 * Returns {@code true} if the specified object is the same object
995 * as this object, or if it is also a {@link List} and the sequence
996 * of elements returned by an {@linkplain List#iterator() iterator}
997 * over the specified list is the same as the sequence returned by
998 * an iterator over this list. The two sequences are considered to
999 * be the same if they have the same length and corresponding
1000 * elements at the same position in the sequence are <em>equal</em>.
1001 * Two elements {@code e1} and {@code e2} are considered
1002 * <em>equal</em> if {@code (e1==null ? e2==null : e1.equals(e2))}.
1003 *
1004 * @param o the object to be compared for equality with this list
1005 * @return {@code true} if the specified object is equal to this list
1006 */
1007 public boolean equals(Object o) {
1008 if (o == this)
1009 return true;
1010 if (!(o instanceof List))
1011 return false;
1012
1013 List<?> list = (List<?>)(o);
1014 Iterator<?> it = list.iterator();
1015 Object[] elements = getArray();
1016 int len = elements.length;
1017 for (int i = 0; i < len; ++i)
1018 if (!it.hasNext() || !eq(elements[i], it.next()))
1019 return false;
1020 if (it.hasNext())
1021 return false;
1022 return true;
1023 }
1024
1025 /**
1026 * Returns the hash code value for this list.
1027 *
1028 * <p>This implementation uses the definition in {@link List#hashCode}.
1029 *
1030 * @return the hash code value for this list
1031 */
1032 public int hashCode() {
1033 int hashCode = 1;
1034 Object[] elements = getArray();
1035 int len = elements.length;
1036 for (int i = 0; i < len; ++i) {
1037 Object obj = elements[i];
1038 hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
1039 }
1040 return hashCode;
1041 }
1042
1043 /**
1044 * Returns an iterator over the elements in this list in proper sequence.
1045 *
1046 * <p>The returned iterator provides a snapshot of the state of the list
1047 * when the iterator was constructed. No synchronization is needed while
1048 * traversing the iterator. The iterator does <em>NOT</em> support the
1049 * {@code remove} method.
1050 *
1051 * @return an iterator over the elements in this list in proper sequence
1052 */
1053 public Iterator<E> iterator() {
1054 return new COWIterator<E>(getArray(), 0);
1055 }
1056
1057 /**
1058 * {@inheritDoc}
1059 *
1060 * <p>The returned iterator provides a snapshot of the state of the list
1061 * when the iterator was constructed. No synchronization is needed while
1062 * traversing the iterator. The iterator does <em>NOT</em> support the
1063 * {@code remove}, {@code set} or {@code add} methods.
1064 */
1065 public ListIterator<E> listIterator() {
1066 return new COWIterator<E>(getArray(), 0);
1067 }
1068
1069 /**
1070 * {@inheritDoc}
1071 *
1072 * <p>The returned iterator provides a snapshot of the state of the list
1073 * when the iterator was constructed. No synchronization is needed while
1074 * traversing the iterator. The iterator does <em>NOT</em> support the
1075 * {@code remove}, {@code set} or {@code add} methods.
1076 *
1077 * @throws IndexOutOfBoundsException {@inheritDoc}
1078 */
1079 public ListIterator<E> listIterator(int index) {
1080 Object[] elements = getArray();
1081 int len = elements.length;
1082 if (index < 0 || index > len)
1083 throw new IndexOutOfBoundsException("Index: "+index);
1084
1085 return new COWIterator<E>(elements, index);
1086 }
1087
1088 public Spliterator<E> spliterator() {
1089 return Spliterators.spliterator
1090 (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED);
1091 }
1092
1093 static final class COWIterator<E> implements ListIterator<E> {
1094 /** Snapshot of the array */
1095 private final Object[] snapshot;
1096 /** Index of element to be returned by subsequent call to next. */
1097 private int cursor;
1098
1099 private COWIterator(Object[] elements, int initialCursor) {
1100 cursor = initialCursor;
1101 snapshot = elements;
1102 }
1103
1104 public boolean hasNext() {
1105 return cursor < snapshot.length;
1106 }
1107
1108 public boolean hasPrevious() {
1109 return cursor > 0;
1110 }
1111
1112 @SuppressWarnings("unchecked")
1113 public E next() {
1114 if (! hasNext())
1115 throw new NoSuchElementException();
1116 return (E) snapshot[cursor++];
1117 }
1118
1119 @SuppressWarnings("unchecked")
1120 public E previous() {
1121 if (! hasPrevious())
1122 throw new NoSuchElementException();
1123 return (E) snapshot[--cursor];
1124 }
1125
1126 public int nextIndex() {
1127 return cursor;
1128 }
1129
1130 public int previousIndex() {
1131 return cursor-1;
1132 }
1133
1134 /**
1135 * Not supported. Always throws UnsupportedOperationException.
1136 * @throws UnsupportedOperationException always; {@code remove}
1137 * is not supported by this iterator.
1138 */
1139 public void remove() {
1140 throw new UnsupportedOperationException();
1141 }
1142
1143 /**
1144 * Not supported. Always throws UnsupportedOperationException.
1145 * @throws UnsupportedOperationException always; {@code set}
1146 * is not supported by this iterator.
1147 */
1148 public void set(E e) {
1149 throw new UnsupportedOperationException();
1150 }
1151
1152 /**
1153 * Not supported. Always throws UnsupportedOperationException.
1154 * @throws UnsupportedOperationException always; {@code add}
1155 * is not supported by this iterator.
1156 */
1157 public void add(E e) {
1158 throw new UnsupportedOperationException();
1159 }
1160 }
1161
1162 /**
1163 * Returns a view of the portion of this list between
1164 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1165 * The returned list is backed by this list, so changes in the
1166 * returned list are reflected in this list.
1167 *
1168 * <p>The semantics of the list returned by this method become
1169 * undefined if the backing list (i.e., this list) is modified in
1170 * any way other than via the returned list.
1171 *
1172 * @param fromIndex low endpoint (inclusive) of the subList
1173 * @param toIndex high endpoint (exclusive) of the subList
1174 * @return a view of the specified range within this list
1175 * @throws IndexOutOfBoundsException {@inheritDoc}
1176 */
1177 public List<E> subList(int fromIndex, int toIndex) {
1178 final ReentrantLock lock = this.lock;
1179 lock.lock();
1180 try {
1181 Object[] elements = getArray();
1182 int len = elements.length;
1183 if (fromIndex < 0 || toIndex > len || fromIndex > toIndex)
1184 throw new IndexOutOfBoundsException();
1185 return new COWSubList<E>(this, fromIndex, toIndex);
1186 } finally {
1187 lock.unlock();
1188 }
1189 }
1190
1191 /**
1192 * Sublist for CopyOnWriteArrayList.
1193 * This class extends AbstractList merely for convenience, to
1194 * avoid having to define addAll, etc. This doesn't hurt, but
1195 * is wasteful. This class does not need or use modCount
1196 * mechanics in AbstractList, but does need to check for
1197 * concurrent modification using similar mechanics. On each
1198 * operation, the array that we expect the backing list to use
1199 * is checked and updated. Since we do this for all of the
1200 * base operations invoked by those defined in AbstractList,
1201 * all is well. While inefficient, this is not worth
1202 * improving. The kinds of list operations inherited from
1203 * AbstractList are already so slow on COW sublists that
1204 * adding a bit more space/time doesn't seem even noticeable.
1205 */
1206 private static class COWSubList<E>
1207 extends AbstractList<E>
1208 implements RandomAccess
1209 {
1210 private final CopyOnWriteArrayList<E> l;
1211 private final int offset;
1212 private int size;
1213 private Object[] expectedArray;
1214
1215 // only call this holding l's lock
1216 COWSubList(CopyOnWriteArrayList<E> list,
1217 int fromIndex, int toIndex) {
1218 l = list;
1219 expectedArray = l.getArray();
1220 offset = fromIndex;
1221 size = toIndex - fromIndex;
1222 }
1223
1224 // only call this holding l's lock
1225 private void checkForComodification() {
1226 if (l.getArray() != expectedArray)
1227 throw new ConcurrentModificationException();
1228 }
1229
1230 // only call this holding l's lock
1231 private void rangeCheck(int index) {
1232 if (index < 0 || index >= size)
1233 throw new IndexOutOfBoundsException("Index: "+index+
1234 ",Size: "+size);
1235 }
1236
1237 public E set(int index, E element) {
1238 final ReentrantLock lock = l.lock;
1239 lock.lock();
1240 try {
1241 rangeCheck(index);
1242 checkForComodification();
1243 E x = l.set(index+offset, element);
1244 expectedArray = l.getArray();
1245 return x;
1246 } finally {
1247 lock.unlock();
1248 }
1249 }
1250
1251 public E get(int index) {
1252 final ReentrantLock lock = l.lock;
1253 lock.lock();
1254 try {
1255 rangeCheck(index);
1256 checkForComodification();
1257 return l.get(index+offset);
1258 } finally {
1259 lock.unlock();
1260 }
1261 }
1262
1263 public int size() {
1264 final ReentrantLock lock = l.lock;
1265 lock.lock();
1266 try {
1267 checkForComodification();
1268 return size;
1269 } finally {
1270 lock.unlock();
1271 }
1272 }
1273
1274 public void add(int index, E element) {
1275 final ReentrantLock lock = l.lock;
1276 lock.lock();
1277 try {
1278 checkForComodification();
1279 if (index < 0 || index > size)
1280 throw new IndexOutOfBoundsException();
1281 l.add(index+offset, element);
1282 expectedArray = l.getArray();
1283 size++;
1284 } finally {
1285 lock.unlock();
1286 }
1287 }
1288
1289 public void clear() {
1290 final ReentrantLock lock = l.lock;
1291 lock.lock();
1292 try {
1293 checkForComodification();
1294 l.removeRange(offset, offset+size);
1295 expectedArray = l.getArray();
1296 size = 0;
1297 } finally {
1298 lock.unlock();
1299 }
1300 }
1301
1302 public E remove(int index) {
1303 final ReentrantLock lock = l.lock;
1304 lock.lock();
1305 try {
1306 rangeCheck(index);
1307 checkForComodification();
1308 E result = l.remove(index+offset);
1309 expectedArray = l.getArray();
1310 size--;
1311 return result;
1312 } finally {
1313 lock.unlock();
1314 }
1315 }
1316
1317 public boolean remove(Object o) {
1318 int index = indexOf(o);
1319 if (index == -1)
1320 return false;
1321 remove(index);
1322 return true;
1323 }
1324
1325 public Iterator<E> iterator() {
1326 final ReentrantLock lock = l.lock;
1327 lock.lock();
1328 try {
1329 checkForComodification();
1330 return new COWSubListIterator<E>(l, 0, offset, size);
1331 } finally {
1332 lock.unlock();
1333 }
1334 }
1335
1336 public ListIterator<E> listIterator(int index) {
1337 final ReentrantLock lock = l.lock;
1338 lock.lock();
1339 try {
1340 checkForComodification();
1341 if (index < 0 || index > size)
1342 throw new IndexOutOfBoundsException("Index: "+index+
1343 ", Size: "+size);
1344 return new COWSubListIterator<E>(l, index, offset, size);
1345 } finally {
1346 lock.unlock();
1347 }
1348 }
1349
1350 public List<E> subList(int fromIndex, int toIndex) {
1351 final ReentrantLock lock = l.lock;
1352 lock.lock();
1353 try {
1354 checkForComodification();
1355 if (fromIndex < 0 || toIndex > size)
1356 throw new IndexOutOfBoundsException();
1357 return new COWSubList<E>(l, fromIndex + offset,
1358 toIndex + offset);
1359 } finally {
1360 lock.unlock();
1361 }
1362 }
1363
1364 public void forEach(Consumer<? super E> action) {
1365 if (action == null) throw new NullPointerException();
1366 int lo = offset;
1367 int hi = offset + size;
1368 Object[] a = expectedArray;
1369 if (l.getArray() != a)
1370 throw new ConcurrentModificationException();
1371 if (lo < 0 || hi > a.length)
1372 throw new IndexOutOfBoundsException();
1373 for (int i = lo; i < hi; ++i) {
1374 @SuppressWarnings("unchecked") E e = (E) a[i];
1375 action.accept(e);
1376 }
1377 }
1378
1379 public void replaceAll(UnaryOperator<E> operator) {
1380 if (operator == null) throw new NullPointerException();
1381 final ReentrantLock lock = l.lock;
1382 lock.lock();
1383 try {
1384 int lo = offset;
1385 int hi = offset + size;
1386 Object[] elements = expectedArray;
1387 if (l.getArray() != elements)
1388 throw new ConcurrentModificationException();
1389 int len = elements.length;
1390 if (lo < 0 || hi > len)
1391 throw new IndexOutOfBoundsException();
1392 Object[] newElements = Arrays.copyOf(elements, len);
1393 for (int i = lo; i < hi; ++i) {
1394 @SuppressWarnings("unchecked") E e = (E) elements[i];
1395 newElements[i] = operator.apply(e);
1396 }
1397 l.setArray(expectedArray = newElements);
1398 } finally {
1399 lock.unlock();
1400 }
1401 }
1402
1403 public void sort(Comparator<? super E> c) {
1404 final ReentrantLock lock = l.lock;
1405 lock.lock();
1406 try {
1407 int lo = offset;
1408 int hi = offset + size;
1409 Object[] elements = expectedArray;
1410 if (l.getArray() != elements)
1411 throw new ConcurrentModificationException();
1412 int len = elements.length;
1413 if (lo < 0 || hi > len)
1414 throw new IndexOutOfBoundsException();
1415 Object[] newElements = Arrays.copyOf(elements, len);
1416 @SuppressWarnings("unchecked") E[] es = (E[])newElements;
1417 Arrays.sort(es, lo, hi, c);
1418 l.setArray(expectedArray = newElements);
1419 } finally {
1420 lock.unlock();
1421 }
1422 }
1423
1424 public boolean removeAll(Collection<?> c) {
1425 if (c == null) throw new NullPointerException();
1426 boolean removed = false;
1427 final ReentrantLock lock = l.lock;
1428 lock.lock();
1429 try {
1430 int n = size;
1431 if (n > 0) {
1432 int lo = offset;
1433 int hi = offset + n;
1434 Object[] elements = expectedArray;
1435 if (l.getArray() != elements)
1436 throw new ConcurrentModificationException();
1437 int len = elements.length;
1438 if (lo < 0 || hi > len)
1439 throw new IndexOutOfBoundsException();
1440 int newSize = 0;
1441 Object[] temp = new Object[n];
1442 for (int i = lo; i < hi; ++i) {
1443 Object element = elements[i];
1444 if (!c.contains(element))
1445 temp[newSize++] = element;
1446 }
1447 if (newSize != n) {
1448 Object[] newElements = new Object[len - n + newSize];
1449 System.arraycopy(elements, 0, newElements, 0, lo);
1450 System.arraycopy(temp, 0, newElements, lo, newSize);
1451 System.arraycopy(elements, hi, newElements,
1452 lo + newSize, len - hi);
1453 size = newSize;
1454 removed = true;
1455 l.setArray(expectedArray = newElements);
1456 }
1457 }
1458 } finally {
1459 lock.unlock();
1460 }
1461 return removed;
1462 }
1463
1464 public boolean retainAll(Collection<?> c) {
1465 if (c == null) throw new NullPointerException();
1466 boolean removed = false;
1467 final ReentrantLock lock = l.lock;
1468 lock.lock();
1469 try {
1470 int n = size;
1471 if (n > 0) {
1472 int lo = offset;
1473 int hi = offset + n;
1474 Object[] elements = expectedArray;
1475 if (l.getArray() != elements)
1476 throw new ConcurrentModificationException();
1477 int len = elements.length;
1478 if (lo < 0 || hi > len)
1479 throw new IndexOutOfBoundsException();
1480 int newSize = 0;
1481 Object[] temp = new Object[n];
1482 for (int i = lo; i < hi; ++i) {
1483 Object element = elements[i];
1484 if (c.contains(element))
1485 temp[newSize++] = element;
1486 }
1487 if (newSize != n) {
1488 Object[] newElements = new Object[len - n + newSize];
1489 System.arraycopy(elements, 0, newElements, 0, lo);
1490 System.arraycopy(temp, 0, newElements, lo, newSize);
1491 System.arraycopy(elements, hi, newElements,
1492 lo + newSize, len - hi);
1493 size = newSize;
1494 removed = true;
1495 l.setArray(expectedArray = newElements);
1496 }
1497 }
1498 } finally {
1499 lock.unlock();
1500 }
1501 return removed;
1502 }
1503
1504 public boolean removeIf(Predicate<? super E> filter) {
1505 if (filter == null) throw new NullPointerException();
1506 boolean removed = false;
1507 final ReentrantLock lock = l.lock;
1508 lock.lock();
1509 try {
1510 int n = size;
1511 if (n > 0) {
1512 int lo = offset;
1513 int hi = offset + n;
1514 Object[] elements = expectedArray;
1515 if (l.getArray() != elements)
1516 throw new ConcurrentModificationException();
1517 int len = elements.length;
1518 if (lo < 0 || hi > len)
1519 throw new IndexOutOfBoundsException();
1520 int newSize = 0;
1521 Object[] temp = new Object[n];
1522 for (int i = lo; i < hi; ++i) {
1523 @SuppressWarnings("unchecked") E e = (E) elements[i];
1524 if (!filter.test(e))
1525 temp[newSize++] = e;
1526 }
1527 if (newSize != n) {
1528 Object[] newElements = new Object[len - n + newSize];
1529 System.arraycopy(elements, 0, newElements, 0, lo);
1530 System.arraycopy(temp, 0, newElements, lo, newSize);
1531 System.arraycopy(elements, hi, newElements,
1532 lo + newSize, len - hi);
1533 size = newSize;
1534 removed = true;
1535 l.setArray(expectedArray = newElements);
1536 }
1537 }
1538 } finally {
1539 lock.unlock();
1540 }
1541 return removed;
1542 }
1543
1544 public Spliterator<E> spliterator() {
1545 int lo = offset;
1546 int hi = offset + size;
1547 Object[] a = expectedArray;
1548 if (l.getArray() != a)
1549 throw new ConcurrentModificationException();
1550 if (lo < 0 || hi > a.length)
1551 throw new IndexOutOfBoundsException();
1552 return Spliterators.spliterator
1553 (a, lo, hi, Spliterator.IMMUTABLE | Spliterator.ORDERED);
1554 }
1555
1556 }
1557
1558 private static class COWSubListIterator<E> implements ListIterator<E> {
1559 private final ListIterator<E> it;
1560 private final int offset;
1561 private final int size;
1562
1563 COWSubListIterator(List<E> l, int index, int offset, int size) {
1564 this.offset = offset;
1565 this.size = size;
1566 it = l.listIterator(index+offset);
1567 }
1568
1569 public boolean hasNext() {
1570 return nextIndex() < size;
1571 }
1572
1573 public E next() {
1574 if (hasNext())
1575 return it.next();
1576 else
1577 throw new NoSuchElementException();
1578 }
1579
1580 public boolean hasPrevious() {
1581 return previousIndex() >= 0;
1582 }
1583
1584 public E previous() {
1585 if (hasPrevious())
1586 return it.previous();
1587 else
1588 throw new NoSuchElementException();
1589 }
1590
1591 public int nextIndex() {
1592 return it.nextIndex() - offset;
1593 }
1594
1595 public int previousIndex() {
1596 return it.previousIndex() - offset;
1597 }
1598
1599 public void remove() {
1600 throw new UnsupportedOperationException();
1601 }
1602
1603 public void set(E e) {
1604 throw new UnsupportedOperationException();
1605 }
1606
1607 public void add(E e) {
1608 throw new UnsupportedOperationException();
1609 }
1610 }
1611
1612 // Support for resetting lock while deserializing
1613 private void resetLock() {
1614 UNSAFE.putObjectVolatile(this, lockOffset, new ReentrantLock());
1615 }
1616 private static final sun.misc.Unsafe UNSAFE;
1617 private static final long lockOffset;
1618 static {
1619 try {
1620 UNSAFE = sun.misc.Unsafe.getUnsafe();
1621 Class<?> k = CopyOnWriteArrayList.class;
1622 lockOffset = UNSAFE.objectFieldOffset
1623 (k.getDeclaredField("lock"));
1624 } catch (Exception e) {
1625 throw new Error(e);
1626 }
1627 }
1628 }