ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.65
Committed: Mon May 21 20:49:41 2007 UTC (17 years ago) by jsr166
Branch: MAIN
Changes since 1.64: +4 -8 lines
Log Message:
6529795: (coll) Iterator.remove() fails if next() threw NoSuchElementException

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