ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.103
Committed: Fri Apr 12 18:44:19 2013 UTC (11 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.102: +5 -5 lines
Log Message:
addAllAbsent: optimize away one array allocation

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