ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.156
Committed: Wed Mar 20 01:21:51 2019 UTC (5 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.155: +2 -1 lines
Log Message:
8221120: CopyOnWriteArrayList.set should always have volatile write semantics

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