ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.47
Committed: Tue Jun 21 07:45:09 2005 UTC (18 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.46: +3 -3 lines
Log Message:
doc fixes

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