ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.43
Committed: Wed Jun 8 12:58:59 2005 UTC (18 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.42: +20 -17 lines
Log Message:
Incorporate review comments

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