ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.44
Committed: Thu Jun 9 23:12:28 2005 UTC (18 years, 11 months ago) by dl
Branch: MAIN
Changes since 1.43: +0 -2 lines
Log Message:
remove redundant arrayCopy call

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 }
802 for (E e : c)
803 newElements[index++] = e;
804 setArray(newElements);
805 }
806 } finally {
807 lock.unlock();
808 }
809 return numNew != 0;
810 }
811
812 /**
813 * Save the state of the list to a stream (i.e., serialize it).
814 *
815 * @serialData The length of the array backing the list is emitted
816 * (int), followed by all of its elements (each an Object)
817 * in the proper order.
818 * @param s the stream
819 */
820 private void writeObject(java.io.ObjectOutputStream s)
821 throws java.io.IOException{
822
823 // Write out element count, and any hidden stuff
824 s.defaultWriteObject();
825
826 Object[] elements = getArray();
827 int len = elements.length;
828 // Write out array length
829 s.writeInt(len);
830
831 // Write out all elements in the proper order.
832 for (int i = 0; i < len; i++)
833 s.writeObject(elements[i]);
834 }
835
836 /**
837 * Reconstitute the list from a stream (i.e., deserialize it).
838 * @param s the stream
839 */
840 private void readObject(java.io.ObjectInputStream s)
841 throws java.io.IOException, ClassNotFoundException {
842
843 // Read in size, and any hidden stuff
844 s.defaultReadObject();
845
846 // bind to new lock
847 resetLock();
848
849 // Read in array length and allocate array
850 int len = s.readInt();
851 Object[] elements = new Object[len];
852
853 // Read in all elements in the proper order.
854 for (int i = 0; i < len; i++)
855 elements[i] = s.readObject();
856 setArray(elements);
857
858 }
859
860 /**
861 * Returns a string representation of this list, containing
862 * the String representation of each element.
863 */
864 public String toString() {
865 Object[] elements = getArray();
866 int maxIndex = elements.length - 1;
867 StringBuilder sb = new StringBuilder();
868 sb.append("[");
869 for (int i = 0; i <= maxIndex; i++) {
870 sb.append(String.valueOf(elements[i]));
871 if (i < maxIndex)
872 sb.append(", ");
873 }
874 sb.append("]");
875 return sb.toString();
876 }
877
878 /**
879 * Compares the specified object with this list for equality.
880 * Returns true if and only if the specified object is also a {@link
881 * List}, both lists have the same size, and all corresponding pairs
882 * of elements in the two lists are <em>equal</em>. (Two elements
883 * <tt>e1</tt> and <tt>e2</tt> are <em>equal</em> if <tt>(e1==null ?
884 * e2==null : e1.equals(e2))</tt>.) In other words, two lists are
885 * defined to be equal if they contain the same elements in the same
886 * order.
887 *
888 * @param o the object to be compared for equality with this list
889 * @return <tt>true</tt> if the specified object is equal to this list
890 */
891 public boolean equals(Object o) {
892 if (o == this)
893 return true;
894 if (!(o instanceof List))
895 return false;
896
897 List<?> l2 = (List<?>)(o);
898 if (size() != l2.size())
899 return false;
900
901 ListIterator<?> e1 = listIterator();
902 ListIterator<?> e2 = l2.listIterator();
903 while (e1.hasNext()) {
904 if (!eq(e1.next(), e2.next()))
905 return false;
906 }
907 return true;
908 }
909
910 /**
911 * Returns the hash code value for this list.
912 *
913 * <p> This implementation uses the definition in {@link
914 * List#hashCode}.
915 * @return the hash code
916 */
917 public int hashCode() {
918 int hashCode = 1;
919 Object[] elements = getArray();
920 int len = elements.length;
921 for (int i = 0; i < len; ++i) {
922 Object obj = elements[i];
923 hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
924 }
925 return hashCode;
926 }
927
928 /**
929 * Returns an iterator over the elements in this list in proper sequence.
930 *
931 * <p>The returned iterator provides a snapshot of the state of the list
932 * when the iterator was constructed. No synchronization is needed while
933 * traversing the iterator. The iterator does <em>NOT</em> support the
934 * <tt>remove</tt> method.
935 *
936 * @return an iterator over the elements in this list in proper sequence
937 */
938 public Iterator<E> iterator() {
939 return new COWIterator<E>(getArray(), 0);
940 }
941
942 /**
943 * {@inheritDoc}
944 *
945 * <p>The returned iterator provides a snapshot of the state of the list
946 * when the iterator was constructed. No synchronization is needed while
947 * traversing the iterator. The iterator does <em>NOT</em> support the
948 * <tt>remove</tt>, <tt>set</tt> or <tt>add</tt> methods.
949 */
950 public ListIterator<E> listIterator() {
951 return new COWIterator<E>(getArray(), 0);
952 }
953
954 /**
955 * {@inheritDoc}
956 *
957 * <p>The list iterator returned by this implementation will throw an
958 * <tt>UnsupportedOperationException</tt> in its <tt>remove</tt>,
959 * <tt>set</tt> and <tt>add</tt> methods.
960 *
961 * @throws IndexOutOfBoundsException {@inheritDoc}
962 */
963 public ListIterator<E> listIterator(final int index) {
964 Object[] elements = getArray();
965 int len = elements.length;
966 if (index < 0 || index > len)
967 throw new IndexOutOfBoundsException("Index: " + index);
968
969 return new COWIterator<E>(getArray(), index);
970 }
971
972 private static class COWIterator<E> implements ListIterator<E> {
973 /** Snapshot of the array **/
974 private final Object[] snapshot;
975 /** Index of element to be returned by subsequent call to next. */
976 private int cursor;
977
978 private COWIterator(Object[] elements, int initialCursor) {
979 cursor = initialCursor;
980 snapshot = elements;
981 }
982
983 public boolean hasNext() {
984 return cursor < snapshot.length;
985 }
986
987 public boolean hasPrevious() {
988 return cursor > 0;
989 }
990
991 public E next() {
992 try {
993 return (E)(snapshot[cursor++]);
994 } catch (IndexOutOfBoundsException ex) {
995 throw new NoSuchElementException();
996 }
997 }
998
999 public E previous() {
1000 try {
1001 return (E)(snapshot[--cursor]);
1002 } catch (IndexOutOfBoundsException e) {
1003 throw new NoSuchElementException();
1004 }
1005 }
1006
1007 public int nextIndex() {
1008 return cursor;
1009 }
1010
1011 public int previousIndex() {
1012 return cursor - 1;
1013 }
1014
1015 /**
1016 * Not supported. Always throws UnsupportedOperationException.
1017 * @throws UnsupportedOperationException always; <tt>remove</tt>
1018 * is not supported by this iterator.
1019 */
1020 public void remove() {
1021 throw new UnsupportedOperationException();
1022 }
1023
1024 /**
1025 * Not supported. Always throws UnsupportedOperationException.
1026 * @throws UnsupportedOperationException always; <tt>set</tt>
1027 * is not supported by this iterator.
1028 */
1029 public void set(E e) {
1030 throw new UnsupportedOperationException();
1031 }
1032
1033 /**
1034 * Not supported. Always throws UnsupportedOperationException.
1035 * @throws UnsupportedOperationException always; <tt>add</tt>
1036 * is not supported by this iterator.
1037 */
1038 public void add(E e) {
1039 throw new UnsupportedOperationException();
1040 }
1041 }
1042
1043 /**
1044 * Returns a view of the portion of this list between
1045 * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
1046 * The returned list is backed by this list, so changes in the
1047 * returned list are reflected in this list, and vice-versa.
1048 * While mutative operations are supported, they are probably not
1049 * very useful for CopyOnWriteArrayLists.
1050 *
1051 * <p>The semantics of the list returned by this method become
1052 * undefined if the backing list (i.e., this list) is
1053 * <i>structurally modified</i> in any way other than via the
1054 * returned list. (Structural modifications are those that change
1055 * the size of the list, or otherwise perturb it in such a fashion
1056 * that iterations in progress may yield incorrect results.)
1057 *
1058 * @param fromIndex low endpoint (inclusive) of the subList
1059 * @param toIndex high endpoint (exclusive) of the subList
1060 * @return a view of the specified range within this list
1061 * @throws IndexOutOfBoundsException {@inheritDoc}
1062 */
1063 public List<E> subList(int fromIndex, int toIndex) {
1064 final ReentrantLock lock = this.lock;
1065 lock.lock();
1066 try {
1067 Object[] elements = getArray();
1068 int len = elements.length;
1069 if (fromIndex < 0 || toIndex > len || fromIndex > toIndex)
1070 throw new IndexOutOfBoundsException();
1071 return new COWSubList<E>(this, fromIndex, toIndex);
1072 } finally {
1073 lock.unlock();
1074 }
1075 }
1076
1077
1078 /**
1079 * Sublist for CopyOnWriteArrayList.
1080 * This class extends AbstractList merely for convenience, to
1081 * avoid having to define addAll, etc. This doesn't hurt, but
1082 * is wasteful. This class does not need or use modCount
1083 * mechanics in AbstractList, but does need to check for
1084 * concurrent modification using similar mechanics. On each
1085 * operation, the array that we expect the backing list to use
1086 * is checked and updated. Since we do this for all of the
1087 * base operations invoked by those defined in AbstractList,
1088 * all is well. While inefficient, this is not worth
1089 * improving. The kinds of list operations inherited from
1090 * AbstractList are already so slow on COW sublists that
1091 * adding a bit more space/time doesn't seem even noticeable.
1092 */
1093 private static class COWSubList<E> extends AbstractList<E> {
1094 private final CopyOnWriteArrayList<E> l;
1095 private final int offset;
1096 private int size;
1097 private Object[] expectedArray;
1098
1099 private COWSubList(CopyOnWriteArrayList<E> list,
1100 int fromIndex, int toIndex) {
1101 l = list;
1102 expectedArray = l.getArray();
1103 offset = fromIndex;
1104 size = toIndex - fromIndex;
1105 }
1106
1107 // only call this holding l's lock
1108 private void checkForComodification() {
1109 if (l.getArray() != expectedArray)
1110 throw new ConcurrentModificationException();
1111 }
1112
1113 // only call this holding l's lock
1114 private void rangeCheck(int index) {
1115 if (index < 0 || index >= size)
1116 throw new IndexOutOfBoundsException("Index: " + index +
1117 ",Size: " + size);
1118 }
1119
1120 public E set(int index, E element) {
1121 ReentrantLock lock = l.lock;
1122 lock.lock();
1123 try {
1124 rangeCheck(index);
1125 checkForComodification();
1126 E x = l.set(index + offset, element);
1127 expectedArray = l.getArray();
1128 return x;
1129 } finally {
1130 lock.unlock();
1131 }
1132 }
1133
1134 public E get(int index) {
1135 ReentrantLock lock = l.lock;
1136 lock.lock();
1137 try {
1138 rangeCheck(index);
1139 checkForComodification();
1140 return l.get(index + offset);
1141 } finally {
1142 lock.unlock();
1143 }
1144 }
1145
1146 public int size() {
1147 ReentrantLock lock = l.lock;
1148 lock.lock();
1149 try {
1150 checkForComodification();
1151 return size;
1152 } finally {
1153 lock.unlock();
1154 }
1155 }
1156
1157 public void add(int index, E element) {
1158 ReentrantLock lock = l.lock;
1159 lock.lock();
1160 try {
1161 checkForComodification();
1162 if (index<0 || index>size)
1163 throw new IndexOutOfBoundsException();
1164 l.add(index + offset, element);
1165 expectedArray = l.getArray();
1166 size++;
1167 } finally {
1168 lock.unlock();
1169 }
1170 }
1171
1172 public void clear() {
1173 ReentrantLock lock = l.lock;
1174 lock.lock();
1175 try {
1176 checkForComodification();
1177 l.removeRange(offset, offset+size);
1178 expectedArray = l.getArray();
1179 size = 0;
1180 } finally {
1181 lock.unlock();
1182 }
1183 }
1184
1185 public E remove(int index) {
1186 ReentrantLock lock = l.lock;
1187 lock.lock();
1188 try {
1189 rangeCheck(index);
1190 checkForComodification();
1191 E result = l.remove(index + offset);
1192 expectedArray = l.getArray();
1193 size--;
1194 return result;
1195 } finally {
1196 lock.unlock();
1197 }
1198 }
1199
1200 public Iterator<E> iterator() {
1201 ReentrantLock lock = l.lock;
1202 lock.lock();
1203 try {
1204 checkForComodification();
1205 return new COWSubListIterator<E>(l, 0, offset, size);
1206 } finally {
1207 lock.unlock();
1208 }
1209 }
1210
1211 public ListIterator<E> listIterator(final int index) {
1212 ReentrantLock lock = l.lock;
1213 lock.lock();
1214 try {
1215 checkForComodification();
1216 if (index<0 || index>size)
1217 throw new IndexOutOfBoundsException("Index: "+index+
1218 ", Size: "+size);
1219 return new COWSubListIterator<E>(l, index, offset, size);
1220 } finally {
1221 lock.unlock();
1222 }
1223 }
1224
1225 public List<E> subList(int fromIndex, int toIndex) {
1226 ReentrantLock lock = l.lock;
1227 lock.lock();
1228 try {
1229 checkForComodification();
1230 if (fromIndex<0 || toIndex>size)
1231 throw new IndexOutOfBoundsException();
1232 return new COWSubList<E>(l, fromIndex + offset,
1233 toIndex + offset);
1234 } finally {
1235 lock.unlock();
1236 }
1237 }
1238
1239 }
1240
1241
1242 private static class COWSubListIterator<E> implements ListIterator<E> {
1243 private final ListIterator<E> i;
1244 private final int index;
1245 private final int offset;
1246 private final int size;
1247 private COWSubListIterator(List<E> l, int index, int offset,
1248 int size) {
1249 this.index = index;
1250 this.offset = offset;
1251 this.size = size;
1252 i = l.listIterator(index + offset);
1253 }
1254
1255 public boolean hasNext() {
1256 return nextIndex() < size;
1257 }
1258
1259 public E next() {
1260 if (hasNext())
1261 return i.next();
1262 else
1263 throw new NoSuchElementException();
1264 }
1265
1266 public boolean hasPrevious() {
1267 return previousIndex() >= 0;
1268 }
1269
1270 public E previous() {
1271 if (hasPrevious())
1272 return i.previous();
1273 else
1274 throw new NoSuchElementException();
1275 }
1276
1277 public int nextIndex() {
1278 return i.nextIndex() - offset;
1279 }
1280
1281 public int previousIndex() {
1282 return i.previousIndex() - offset;
1283 }
1284
1285 public void remove() {
1286 throw new UnsupportedOperationException();
1287 }
1288
1289 public void set(E e) {
1290 throw new UnsupportedOperationException();
1291 }
1292
1293 public void add(E e) {
1294 throw new UnsupportedOperationException();
1295 }
1296 }
1297
1298 // Support for resetting lock while deserializing
1299 private static final Unsafe unsafe = Unsafe.getUnsafe();
1300 private static final long lockOffset;
1301 static {
1302 try {
1303 lockOffset = unsafe.objectFieldOffset
1304 (CopyOnWriteArrayList.class.getDeclaredField("lock"));
1305 } catch (Exception ex) { throw new Error(ex); }
1306 }
1307 private void resetLock() {
1308 unsafe.putObjectVolatile(this, lockOffset, new ReentrantLock());
1309 }
1310
1311
1312 // Temporary emulations of anticipated new j.u.Arrays functions
1313
1314 private static <T,U> T[] copyOfRange(U[] original, int from, int to,
1315 Class<? extends T[]> newType) {
1316 int newLength = to - from;
1317 if (newLength < 0)
1318 throw new IllegalArgumentException(from + " > " + to);
1319 T[] copy = (T[]) java.lang.reflect.Array.newInstance
1320 (newType.getComponentType(), newLength);
1321 System.arraycopy(original, from, copy, 0,
1322 Math.min(original.length - from, newLength));
1323 return copy;
1324 }
1325
1326 private static <T,U> T[] copyOf(U[] original, int newLength,
1327 Class<? extends T[]> newType) {
1328 T[] copy = (T[]) java.lang.reflect.Array.newInstance
1329 (newType.getComponentType(), newLength);
1330 System.arraycopy(original, 0, copy, 0,
1331 Math.min(original.length, newLength));
1332 return copy;
1333 }
1334
1335 private static <T> T[] copyOf(T[] original, int newLength) {
1336 return (T[]) copyOf(original, newLength, original.getClass());
1337 }
1338 }