ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.54
Committed: Thu Sep 8 21:58:22 2005 UTC (18 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.53: +2 -2 lines
Log Message:
whitespace

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