ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CopyOnWriteArrayList.java
Revision: 1.56
Committed: Wed Sep 14 22:52:49 2005 UTC (18 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.55: +12 -8 lines
Log Message:
happens-before; volatile

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