ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.51
Committed: Fri Sep 2 01:03:08 2005 UTC (18 years, 9 months ago) by brian
Branch: MAIN
Changes since 1.50: +6 -0 lines
Log Message:
Happens-before markup

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