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 |
|
19 |
import java.util.AbstractList; |
20 |
import java.util.Arrays; |
21 |
import java.util.Collection; |
22 |
import java.util.Comparator; |
23 |
import java.util.ConcurrentModificationException; |
24 |
import java.util.Iterator; |
25 |
import java.util.List; |
26 |
import java.util.ListIterator; |
27 |
import java.util.NoSuchElementException; |
28 |
import java.util.RandomAccess; |
29 |
import java.util.Spliterator; |
30 |
import java.util.Spliterators; |
31 |
import java.util.concurrent.locks.ReentrantLock; |
32 |
import java.util.function.Consumer; |
33 |
import java.util.function.Predicate; |
34 |
import java.util.function.UnaryOperator; |
35 |
|
36 |
/** |
37 |
* A thread-safe variant of {@link java.util.ArrayList} in which all mutative |
38 |
* operations ({@code add}, {@code set}, and so on) are implemented by |
39 |
* making a fresh copy of the underlying array. |
40 |
* |
41 |
* <p>This is ordinarily too costly, but may be <em>more</em> efficient |
42 |
* than alternatives when traversal operations vastly outnumber |
43 |
* mutations, and is useful when you cannot or don't want to |
44 |
* synchronize traversals, yet need to preclude interference among |
45 |
* concurrent threads. The "snapshot" style iterator method uses a |
46 |
* reference to the state of the array at the point that the iterator |
47 |
* was created. This array never changes during the lifetime of the |
48 |
* iterator, so interference is impossible and the iterator is |
49 |
* guaranteed not to throw {@code ConcurrentModificationException}. |
50 |
* The iterator will not reflect additions, removals, or changes to |
51 |
* the list since the iterator was created. Element-changing |
52 |
* operations on iterators themselves ({@code remove}, {@code set}, and |
53 |
* {@code add}) are not supported. These methods throw |
54 |
* {@code UnsupportedOperationException}. |
55 |
* |
56 |
* <p>All elements are permitted, including {@code null}. |
57 |
* |
58 |
* <p>Memory consistency effects: As with other concurrent |
59 |
* collections, actions in a thread prior to placing an object into a |
60 |
* {@code CopyOnWriteArrayList} |
61 |
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> |
62 |
* actions subsequent to the access or removal of that element from |
63 |
* the {@code CopyOnWriteArrayList} in another thread. |
64 |
* |
65 |
* <p>This class is a member of the |
66 |
* <a href="{@docRoot}/../technotes/guides/collections/index.html"> |
67 |
* Java Collections Framework</a>. |
68 |
* |
69 |
* @since 1.5 |
70 |
* @author Doug Lea |
71 |
* @param <E> the type of elements held in this list |
72 |
*/ |
73 |
public class CopyOnWriteArrayList<E> |
74 |
implements List<E>, RandomAccess, Cloneable, java.io.Serializable { |
75 |
private static final long serialVersionUID = 8673264195747942595L; |
76 |
|
77 |
/** The lock protecting all mutators */ |
78 |
final transient ReentrantLock lock = new ReentrantLock(); |
79 |
|
80 |
/** The array, accessed only via getArray/setArray. */ |
81 |
private transient volatile Object[] array; |
82 |
|
83 |
/** |
84 |
* Gets the array. Non-private so as to also be accessible |
85 |
* from CopyOnWriteArraySet class. |
86 |
*/ |
87 |
final Object[] getArray() { |
88 |
return array; |
89 |
} |
90 |
|
91 |
/** |
92 |
* Sets the array. |
93 |
*/ |
94 |
final void setArray(Object[] a) { |
95 |
array = a; |
96 |
} |
97 |
|
98 |
/** |
99 |
* Creates an empty list. |
100 |
*/ |
101 |
public CopyOnWriteArrayList() { |
102 |
setArray(new Object[0]); |
103 |
} |
104 |
|
105 |
/** |
106 |
* Creates a list containing the elements of the specified |
107 |
* collection, in the order they are returned by the collection's |
108 |
* iterator. |
109 |
* |
110 |
* @param c the collection of initially held elements |
111 |
* @throws NullPointerException if the specified collection is null |
112 |
*/ |
113 |
public CopyOnWriteArrayList(Collection<? extends E> c) { |
114 |
Object[] elements; |
115 |
if (c.getClass() == CopyOnWriteArrayList.class) |
116 |
elements = ((CopyOnWriteArrayList<?>)c).getArray(); |
117 |
else { |
118 |
elements = c.toArray(); |
119 |
// c.toArray might (incorrectly) not return Object[] (see 6260652) |
120 |
if (elements.getClass() != Object[].class) |
121 |
elements = Arrays.copyOf(elements, elements.length, Object[].class); |
122 |
} |
123 |
setArray(elements); |
124 |
} |
125 |
|
126 |
/** |
127 |
* Creates a list holding a copy of the given array. |
128 |
* |
129 |
* @param toCopyIn the array (a copy of this array is used as the |
130 |
* internal array) |
131 |
* @throws NullPointerException if the specified array is null |
132 |
*/ |
133 |
public CopyOnWriteArrayList(E[] toCopyIn) { |
134 |
setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class)); |
135 |
} |
136 |
|
137 |
/** |
138 |
* Returns the number of elements in this list. |
139 |
* |
140 |
* @return the number of elements in this list |
141 |
*/ |
142 |
public int size() { |
143 |
return getArray().length; |
144 |
} |
145 |
|
146 |
/** |
147 |
* Returns {@code true} if this list contains no elements. |
148 |
* |
149 |
* @return {@code true} if this list contains no elements |
150 |
*/ |
151 |
public boolean isEmpty() { |
152 |
return size() == 0; |
153 |
} |
154 |
|
155 |
/** |
156 |
* Tests for equality, coping with nulls. |
157 |
*/ |
158 |
private static boolean eq(Object o1, Object o2) { |
159 |
return (o1 == null) ? o2 == null : o1.equals(o2); |
160 |
} |
161 |
|
162 |
/** |
163 |
* static version of indexOf, to allow repeated calls without |
164 |
* needing to re-acquire array each time. |
165 |
* @param o element to search for |
166 |
* @param elements the array |
167 |
* @param index first index to search |
168 |
* @param fence one past last index to search |
169 |
* @return index of element, or -1 if absent |
170 |
*/ |
171 |
private static int indexOf(Object o, Object[] elements, |
172 |
int index, int fence) { |
173 |
if (o == null) { |
174 |
for (int i = index; i < fence; i++) |
175 |
if (elements[i] == null) |
176 |
return i; |
177 |
} else { |
178 |
for (int i = index; i < fence; i++) |
179 |
if (o.equals(elements[i])) |
180 |
return i; |
181 |
} |
182 |
return -1; |
183 |
} |
184 |
|
185 |
/** |
186 |
* static version of lastIndexOf. |
187 |
* @param o element to search for |
188 |
* @param elements the array |
189 |
* @param index first index to search |
190 |
* @return index of element, or -1 if absent |
191 |
*/ |
192 |
private static int lastIndexOf(Object o, Object[] elements, int index) { |
193 |
if (o == null) { |
194 |
for (int i = index; i >= 0; i--) |
195 |
if (elements[i] == null) |
196 |
return i; |
197 |
} else { |
198 |
for (int i = index; i >= 0; i--) |
199 |
if (o.equals(elements[i])) |
200 |
return i; |
201 |
} |
202 |
return -1; |
203 |
} |
204 |
|
205 |
/** |
206 |
* Returns {@code true} if this list contains the specified element. |
207 |
* More formally, returns {@code true} if and only if this list contains |
208 |
* at least one element {@code e} such that {@code Objects.equals(o, e)}. |
209 |
* |
210 |
* @param o element whose presence in this list is to be tested |
211 |
* @return {@code true} if this list contains the specified element |
212 |
*/ |
213 |
public boolean contains(Object o) { |
214 |
Object[] elements = getArray(); |
215 |
return indexOf(o, elements, 0, elements.length) >= 0; |
216 |
} |
217 |
|
218 |
/** |
219 |
* {@inheritDoc} |
220 |
*/ |
221 |
public int indexOf(Object o) { |
222 |
Object[] elements = getArray(); |
223 |
return indexOf(o, elements, 0, elements.length); |
224 |
} |
225 |
|
226 |
/** |
227 |
* Returns the index of the first occurrence of the specified element in |
228 |
* this list, searching forwards from {@code index}, or returns -1 if |
229 |
* the element is not found. |
230 |
* More formally, returns the lowest index {@code i} such that |
231 |
* <tt>(i >= index && (e==null ? get(i)==null : e.equals(get(i))))</tt>, |
232 |
* or -1 if there is no such index. |
233 |
* |
234 |
* @param e element to search for |
235 |
* @param index index to start searching from |
236 |
* @return the index of the first occurrence of the element in |
237 |
* this list at position {@code index} or later in the list; |
238 |
* {@code -1} if the element is not found. |
239 |
* @throws IndexOutOfBoundsException if the specified index is negative |
240 |
*/ |
241 |
public int indexOf(E e, int index) { |
242 |
Object[] elements = getArray(); |
243 |
return indexOf(e, elements, index, elements.length); |
244 |
} |
245 |
|
246 |
/** |
247 |
* {@inheritDoc} |
248 |
*/ |
249 |
public int lastIndexOf(Object o) { |
250 |
Object[] elements = getArray(); |
251 |
return lastIndexOf(o, elements, elements.length - 1); |
252 |
} |
253 |
|
254 |
/** |
255 |
* Returns the index of the last occurrence of the specified element in |
256 |
* this list, searching backwards from {@code index}, or returns -1 if |
257 |
* the element is not found. |
258 |
* More formally, returns the highest index {@code i} such that |
259 |
* <tt>(i <= index && (e==null ? get(i)==null : e.equals(get(i))))</tt>, |
260 |
* or -1 if there is no such index. |
261 |
* |
262 |
* @param e element to search for |
263 |
* @param index index to start searching backwards from |
264 |
* @return the index of the last occurrence of the element at position |
265 |
* less than or equal to {@code index} in this list; |
266 |
* -1 if the element is not found. |
267 |
* @throws IndexOutOfBoundsException if the specified index is greater |
268 |
* than or equal to the current size of this list |
269 |
*/ |
270 |
public int lastIndexOf(E e, int index) { |
271 |
Object[] elements = getArray(); |
272 |
return lastIndexOf(e, elements, index); |
273 |
} |
274 |
|
275 |
/** |
276 |
* Returns a shallow copy of this list. (The elements themselves |
277 |
* are not copied.) |
278 |
* |
279 |
* @return a clone of this list |
280 |
*/ |
281 |
public Object clone() { |
282 |
try { |
283 |
@SuppressWarnings("unchecked") |
284 |
CopyOnWriteArrayList<E> clone = |
285 |
(CopyOnWriteArrayList<E>) super.clone(); |
286 |
clone.resetLock(); |
287 |
return clone; |
288 |
} catch (CloneNotSupportedException e) { |
289 |
// this shouldn't happen, since we are Cloneable |
290 |
throw new InternalError(); |
291 |
} |
292 |
} |
293 |
|
294 |
/** |
295 |
* Returns an array containing all of the elements in this list |
296 |
* in proper sequence (from first to last element). |
297 |
* |
298 |
* <p>The returned array will be "safe" in that no references to it are |
299 |
* maintained by this list. (In other words, this method must allocate |
300 |
* a new array). The caller is thus free to modify the returned array. |
301 |
* |
302 |
* <p>This method acts as bridge between array-based and collection-based |
303 |
* APIs. |
304 |
* |
305 |
* @return an array containing all the elements in this list |
306 |
*/ |
307 |
public Object[] toArray() { |
308 |
Object[] elements = getArray(); |
309 |
return Arrays.copyOf(elements, elements.length); |
310 |
} |
311 |
|
312 |
/** |
313 |
* Returns an array containing all of the elements in this list in |
314 |
* proper sequence (from first to last element); the runtime type of |
315 |
* the returned array is that of the specified array. If the list fits |
316 |
* in the specified array, it is returned therein. Otherwise, a new |
317 |
* array is allocated with the runtime type of the specified array and |
318 |
* the size of this list. |
319 |
* |
320 |
* <p>If this list fits in the specified array with room to spare |
321 |
* (i.e., the array has more elements than this list), the element in |
322 |
* the array immediately following the end of the list is set to |
323 |
* {@code null}. (This is useful in determining the length of this |
324 |
* list <i>only</i> if the caller knows that this list does not contain |
325 |
* any null elements.) |
326 |
* |
327 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
328 |
* array-based and collection-based APIs. Further, this method allows |
329 |
* precise control over the runtime type of the output array, and may, |
330 |
* under certain circumstances, be used to save allocation costs. |
331 |
* |
332 |
* <p>Suppose {@code x} is a list known to contain only strings. |
333 |
* The following code can be used to dump the list into a newly |
334 |
* allocated array of {@code String}: |
335 |
* |
336 |
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre> |
337 |
* |
338 |
* Note that {@code toArray(new Object[0])} is identical in function to |
339 |
* {@code toArray()}. |
340 |
* |
341 |
* @param a the array into which the elements of the list are to |
342 |
* be stored, if it is big enough; otherwise, a new array of the |
343 |
* same runtime type is allocated for this purpose. |
344 |
* @return an array containing all the elements in this list |
345 |
* @throws ArrayStoreException if the runtime type of the specified array |
346 |
* is not a supertype of the runtime type of every element in |
347 |
* this list |
348 |
* @throws NullPointerException if the specified array is null |
349 |
*/ |
350 |
@SuppressWarnings("unchecked") |
351 |
public <T> T[] toArray(T[] a) { |
352 |
Object[] elements = getArray(); |
353 |
int len = elements.length; |
354 |
if (a.length < len) |
355 |
return (T[]) Arrays.copyOf(elements, len, a.getClass()); |
356 |
else { |
357 |
System.arraycopy(elements, 0, a, 0, len); |
358 |
if (a.length > len) |
359 |
a[len] = null; |
360 |
return a; |
361 |
} |
362 |
} |
363 |
|
364 |
// Positional Access Operations |
365 |
|
366 |
@SuppressWarnings("unchecked") |
367 |
private E get(Object[] a, int index) { |
368 |
return (E) a[index]; |
369 |
} |
370 |
|
371 |
/** |
372 |
* {@inheritDoc} |
373 |
* |
374 |
* @throws IndexOutOfBoundsException {@inheritDoc} |
375 |
*/ |
376 |
public E get(int index) { |
377 |
return get(getArray(), index); |
378 |
} |
379 |
|
380 |
/** |
381 |
* Replaces the element at the specified position in this list with the |
382 |
* specified element. |
383 |
* |
384 |
* @throws IndexOutOfBoundsException {@inheritDoc} |
385 |
*/ |
386 |
public E set(int index, E element) { |
387 |
final ReentrantLock lock = this.lock; |
388 |
lock.lock(); |
389 |
try { |
390 |
Object[] elements = getArray(); |
391 |
E oldValue = get(elements, index); |
392 |
|
393 |
if (oldValue != element) { |
394 |
int len = elements.length; |
395 |
Object[] newElements = Arrays.copyOf(elements, len); |
396 |
newElements[index] = element; |
397 |
setArray(newElements); |
398 |
} else { |
399 |
// Not quite a no-op; ensures volatile write semantics |
400 |
setArray(elements); |
401 |
} |
402 |
return oldValue; |
403 |
} finally { |
404 |
lock.unlock(); |
405 |
} |
406 |
} |
407 |
|
408 |
/** |
409 |
* Appends the specified element to the end of this list. |
410 |
* |
411 |
* @param e element to be appended to this list |
412 |
* @return {@code true} (as specified by {@link Collection#add}) |
413 |
*/ |
414 |
public boolean add(E e) { |
415 |
final ReentrantLock lock = this.lock; |
416 |
lock.lock(); |
417 |
try { |
418 |
Object[] elements = getArray(); |
419 |
int len = elements.length; |
420 |
Object[] newElements = Arrays.copyOf(elements, len + 1); |
421 |
newElements[len] = e; |
422 |
setArray(newElements); |
423 |
return true; |
424 |
} finally { |
425 |
lock.unlock(); |
426 |
} |
427 |
} |
428 |
|
429 |
/** |
430 |
* Inserts the specified element at the specified position in this |
431 |
* list. Shifts the element currently at that position (if any) and |
432 |
* any subsequent elements to the right (adds one to their indices). |
433 |
* |
434 |
* @throws IndexOutOfBoundsException {@inheritDoc} |
435 |
*/ |
436 |
public void add(int index, E element) { |
437 |
final ReentrantLock lock = this.lock; |
438 |
lock.lock(); |
439 |
try { |
440 |
Object[] elements = getArray(); |
441 |
int len = elements.length; |
442 |
if (index > len || index < 0) |
443 |
throw new IndexOutOfBoundsException("Index: "+index+ |
444 |
", Size: "+len); |
445 |
Object[] newElements; |
446 |
int numMoved = len - index; |
447 |
if (numMoved == 0) |
448 |
newElements = Arrays.copyOf(elements, len + 1); |
449 |
else { |
450 |
newElements = new Object[len + 1]; |
451 |
System.arraycopy(elements, 0, newElements, 0, index); |
452 |
System.arraycopy(elements, index, newElements, index + 1, |
453 |
numMoved); |
454 |
} |
455 |
newElements[index] = element; |
456 |
setArray(newElements); |
457 |
} finally { |
458 |
lock.unlock(); |
459 |
} |
460 |
} |
461 |
|
462 |
/** |
463 |
* Removes the element at the specified position in this list. |
464 |
* Shifts any subsequent elements to the left (subtracts one from their |
465 |
* indices). Returns the element that was removed from the list. |
466 |
* |
467 |
* @throws IndexOutOfBoundsException {@inheritDoc} |
468 |
*/ |
469 |
public E remove(int index) { |
470 |
final ReentrantLock lock = this.lock; |
471 |
lock.lock(); |
472 |
try { |
473 |
Object[] elements = getArray(); |
474 |
int len = elements.length; |
475 |
E oldValue = get(elements, index); |
476 |
int numMoved = len - index - 1; |
477 |
if (numMoved == 0) |
478 |
setArray(Arrays.copyOf(elements, len - 1)); |
479 |
else { |
480 |
Object[] newElements = new Object[len - 1]; |
481 |
System.arraycopy(elements, 0, newElements, 0, index); |
482 |
System.arraycopy(elements, index + 1, newElements, index, |
483 |
numMoved); |
484 |
setArray(newElements); |
485 |
} |
486 |
return oldValue; |
487 |
} finally { |
488 |
lock.unlock(); |
489 |
} |
490 |
} |
491 |
|
492 |
/** |
493 |
* Removes the first occurrence of the specified element from this list, |
494 |
* if it is present. If this list does not contain the element, it is |
495 |
* unchanged. More formally, removes the element with the lowest index |
496 |
* {@code i} such that {@code Objects.equals(o, get(i))} |
497 |
* (if such an element exists). Returns {@code true} if this list |
498 |
* contained the specified element (or equivalently, if this list |
499 |
* changed as a result of the call). |
500 |
* |
501 |
* @param o element to be removed from this list, if present |
502 |
* @return {@code true} if this list contained the specified element |
503 |
*/ |
504 |
public boolean remove(Object o) { |
505 |
Object[] snapshot = getArray(); |
506 |
int index = indexOf(o, snapshot, 0, snapshot.length); |
507 |
return (index < 0) ? false : remove(o, snapshot, index); |
508 |
} |
509 |
|
510 |
/** |
511 |
* A version of remove(Object) using the strong hint that given |
512 |
* recent snapshot contains o at the given index. |
513 |
*/ |
514 |
private boolean remove(Object o, Object[] snapshot, int index) { |
515 |
final ReentrantLock lock = this.lock; |
516 |
lock.lock(); |
517 |
try { |
518 |
Object[] current = getArray(); |
519 |
int len = current.length; |
520 |
if (snapshot != current) findIndex: { |
521 |
int prefix = Math.min(index, len); |
522 |
for (int i = 0; i < prefix; i++) { |
523 |
if (current[i] != snapshot[i] && eq(o, current[i])) { |
524 |
index = i; |
525 |
break findIndex; |
526 |
} |
527 |
} |
528 |
if (index >= len) |
529 |
return false; |
530 |
if (current[index] == o) |
531 |
break findIndex; |
532 |
index = indexOf(o, current, index, len); |
533 |
if (index < 0) |
534 |
return false; |
535 |
} |
536 |
Object[] newElements = new Object[len - 1]; |
537 |
System.arraycopy(current, 0, newElements, 0, index); |
538 |
System.arraycopy(current, index + 1, |
539 |
newElements, index, |
540 |
len - index - 1); |
541 |
setArray(newElements); |
542 |
return true; |
543 |
} finally { |
544 |
lock.unlock(); |
545 |
} |
546 |
} |
547 |
|
548 |
/** |
549 |
* Removes from this list all of the elements whose index is between |
550 |
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. |
551 |
* Shifts any succeeding elements to the left (reduces their index). |
552 |
* This call shortens the list by {@code (toIndex - fromIndex)} elements. |
553 |
* (If {@code toIndex==fromIndex}, this operation has no effect.) |
554 |
* |
555 |
* @param fromIndex index of first element to be removed |
556 |
* @param toIndex index after last element to be removed |
557 |
* @throws IndexOutOfBoundsException if fromIndex or toIndex out of range |
558 |
* ({@code fromIndex < 0 || toIndex > size() || toIndex < fromIndex}) |
559 |
*/ |
560 |
void removeRange(int fromIndex, int toIndex) { |
561 |
final ReentrantLock lock = this.lock; |
562 |
lock.lock(); |
563 |
try { |
564 |
Object[] elements = getArray(); |
565 |
int len = elements.length; |
566 |
|
567 |
if (fromIndex < 0 || toIndex > len || toIndex < fromIndex) |
568 |
throw new IndexOutOfBoundsException(); |
569 |
int newlen = len - (toIndex - fromIndex); |
570 |
int numMoved = len - toIndex; |
571 |
if (numMoved == 0) |
572 |
setArray(Arrays.copyOf(elements, newlen)); |
573 |
else { |
574 |
Object[] newElements = new Object[newlen]; |
575 |
System.arraycopy(elements, 0, newElements, 0, fromIndex); |
576 |
System.arraycopy(elements, toIndex, newElements, |
577 |
fromIndex, numMoved); |
578 |
setArray(newElements); |
579 |
} |
580 |
} finally { |
581 |
lock.unlock(); |
582 |
} |
583 |
} |
584 |
|
585 |
/** |
586 |
* Appends the element, if not present. |
587 |
* |
588 |
* @param e element to be added to this list, if absent |
589 |
* @return {@code true} if the element was added |
590 |
*/ |
591 |
public boolean addIfAbsent(E e) { |
592 |
Object[] snapshot = getArray(); |
593 |
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false : |
594 |
addIfAbsent(e, snapshot); |
595 |
} |
596 |
|
597 |
/** |
598 |
* A version of addIfAbsent using the strong hint that given |
599 |
* recent snapshot does not contain e. |
600 |
*/ |
601 |
private boolean addIfAbsent(E e, Object[] snapshot) { |
602 |
final ReentrantLock lock = this.lock; |
603 |
lock.lock(); |
604 |
try { |
605 |
Object[] current = getArray(); |
606 |
int len = current.length; |
607 |
if (snapshot != current) { |
608 |
// Optimize for lost race to another addXXX operation |
609 |
int common = Math.min(snapshot.length, len); |
610 |
for (int i = 0; i < common; i++) |
611 |
if (current[i] != snapshot[i] && eq(e, current[i])) |
612 |
return false; |
613 |
if (indexOf(e, current, common, len) >= 0) |
614 |
return false; |
615 |
} |
616 |
Object[] newElements = Arrays.copyOf(current, len + 1); |
617 |
newElements[len] = e; |
618 |
setArray(newElements); |
619 |
return true; |
620 |
} finally { |
621 |
lock.unlock(); |
622 |
} |
623 |
} |
624 |
|
625 |
/** |
626 |
* Returns {@code true} if this list contains all of the elements of the |
627 |
* specified collection. |
628 |
* |
629 |
* @param c collection to be checked for containment in this list |
630 |
* @return {@code true} if this list contains all of the elements of the |
631 |
* specified collection |
632 |
* @throws NullPointerException if the specified collection is null |
633 |
* @see #contains(Object) |
634 |
*/ |
635 |
public boolean containsAll(Collection<?> c) { |
636 |
Object[] elements = getArray(); |
637 |
int len = elements.length; |
638 |
for (Object e : c) { |
639 |
if (indexOf(e, elements, 0, len) < 0) |
640 |
return false; |
641 |
} |
642 |
return true; |
643 |
} |
644 |
|
645 |
/** |
646 |
* Removes from this list all of its elements that are contained in |
647 |
* the specified collection. This is a particularly expensive operation |
648 |
* in this class because of the need for an internal temporary array. |
649 |
* |
650 |
* @param c collection containing elements to be removed from this list |
651 |
* @return {@code true} if this list changed as a result of the call |
652 |
* @throws ClassCastException if the class of an element of this list |
653 |
* is incompatible with the specified collection |
654 |
* (<a href="../Collection.html#optional-restrictions">optional</a>) |
655 |
* @throws NullPointerException if this list contains a null element and the |
656 |
* specified collection does not permit null elements |
657 |
* (<a href="../Collection.html#optional-restrictions">optional</a>), |
658 |
* or if the specified collection is null |
659 |
* @see #remove(Object) |
660 |
*/ |
661 |
public boolean removeAll(Collection<?> c) { |
662 |
if (c == null) throw new NullPointerException(); |
663 |
final ReentrantLock lock = this.lock; |
664 |
lock.lock(); |
665 |
try { |
666 |
Object[] elements = getArray(); |
667 |
int len = elements.length; |
668 |
if (len != 0) { |
669 |
// temp array holds those elements we know we want to keep |
670 |
int newlen = 0; |
671 |
Object[] temp = new Object[len]; |
672 |
for (int i = 0; i < len; ++i) { |
673 |
Object element = elements[i]; |
674 |
if (!c.contains(element)) |
675 |
temp[newlen++] = element; |
676 |
} |
677 |
if (newlen != len) { |
678 |
setArray(Arrays.copyOf(temp, newlen)); |
679 |
return true; |
680 |
} |
681 |
} |
682 |
return false; |
683 |
} finally { |
684 |
lock.unlock(); |
685 |
} |
686 |
} |
687 |
|
688 |
/** |
689 |
* Retains only the elements in this list that are contained in the |
690 |
* specified collection. In other words, removes from this list all of |
691 |
* its elements that are not contained in the specified collection. |
692 |
* |
693 |
* @param c collection containing elements to be retained in this list |
694 |
* @return {@code true} if this list changed as a result of the call |
695 |
* @throws ClassCastException if the class of an element of this list |
696 |
* is incompatible with the specified collection |
697 |
* (<a href="../Collection.html#optional-restrictions">optional</a>) |
698 |
* @throws NullPointerException if this list contains a null element and the |
699 |
* specified collection does not permit null elements |
700 |
* (<a href="../Collection.html#optional-restrictions">optional</a>), |
701 |
* or if the specified collection is null |
702 |
* @see #remove(Object) |
703 |
*/ |
704 |
public boolean retainAll(Collection<?> c) { |
705 |
if (c == null) throw new NullPointerException(); |
706 |
final ReentrantLock lock = this.lock; |
707 |
lock.lock(); |
708 |
try { |
709 |
Object[] elements = getArray(); |
710 |
int len = elements.length; |
711 |
if (len != 0) { |
712 |
// temp array holds those elements we know we want to keep |
713 |
int newlen = 0; |
714 |
Object[] temp = new Object[len]; |
715 |
for (int i = 0; i < len; ++i) { |
716 |
Object element = elements[i]; |
717 |
if (c.contains(element)) |
718 |
temp[newlen++] = element; |
719 |
} |
720 |
if (newlen != len) { |
721 |
setArray(Arrays.copyOf(temp, newlen)); |
722 |
return true; |
723 |
} |
724 |
} |
725 |
return false; |
726 |
} finally { |
727 |
lock.unlock(); |
728 |
} |
729 |
} |
730 |
|
731 |
/** |
732 |
* Appends all of the elements in the specified collection that |
733 |
* are not already contained in this list, to the end of |
734 |
* this list, in the order that they are returned by the |
735 |
* specified collection's iterator. |
736 |
* |
737 |
* @param c collection containing elements to be added to this list |
738 |
* @return the number of elements added |
739 |
* @throws NullPointerException if the specified collection is null |
740 |
* @see #addIfAbsent(Object) |
741 |
*/ |
742 |
public int addAllAbsent(Collection<? extends E> c) { |
743 |
Object[] cs = c.toArray(); |
744 |
if (cs.length == 0) |
745 |
return 0; |
746 |
final ReentrantLock lock = this.lock; |
747 |
lock.lock(); |
748 |
try { |
749 |
Object[] elements = getArray(); |
750 |
int len = elements.length; |
751 |
int added = 0; |
752 |
// uniquify and compact elements in cs |
753 |
for (int i = 0; i < cs.length; ++i) { |
754 |
Object e = cs[i]; |
755 |
if (indexOf(e, elements, 0, len) < 0 && |
756 |
indexOf(e, cs, 0, added) < 0) |
757 |
cs[added++] = e; |
758 |
} |
759 |
if (added > 0) { |
760 |
Object[] newElements = Arrays.copyOf(elements, len + added); |
761 |
System.arraycopy(cs, 0, newElements, len, added); |
762 |
setArray(newElements); |
763 |
} |
764 |
return added; |
765 |
} finally { |
766 |
lock.unlock(); |
767 |
} |
768 |
} |
769 |
|
770 |
/** |
771 |
* Removes all of the elements from this list. |
772 |
* The list will be empty after this call returns. |
773 |
*/ |
774 |
public void clear() { |
775 |
final ReentrantLock lock = this.lock; |
776 |
lock.lock(); |
777 |
try { |
778 |
setArray(new Object[0]); |
779 |
} finally { |
780 |
lock.unlock(); |
781 |
} |
782 |
} |
783 |
|
784 |
/** |
785 |
* Appends all of the elements in the specified collection to the end |
786 |
* of this list, in the order that they are returned by the specified |
787 |
* collection's iterator. |
788 |
* |
789 |
* @param c collection containing elements to be added to this list |
790 |
* @return {@code true} if this list changed as a result of the call |
791 |
* @throws NullPointerException if the specified collection is null |
792 |
* @see #add(Object) |
793 |
*/ |
794 |
public boolean addAll(Collection<? extends E> c) { |
795 |
Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ? |
796 |
((CopyOnWriteArrayList<?>)c).getArray() : c.toArray(); |
797 |
if (cs.length == 0) |
798 |
return false; |
799 |
final ReentrantLock lock = this.lock; |
800 |
lock.lock(); |
801 |
try { |
802 |
Object[] elements = getArray(); |
803 |
int len = elements.length; |
804 |
if (len == 0 && cs.getClass() == Object[].class) |
805 |
setArray(cs); |
806 |
else { |
807 |
Object[] newElements = Arrays.copyOf(elements, len + cs.length); |
808 |
System.arraycopy(cs, 0, newElements, len, cs.length); |
809 |
setArray(newElements); |
810 |
} |
811 |
return true; |
812 |
} finally { |
813 |
lock.unlock(); |
814 |
} |
815 |
} |
816 |
|
817 |
/** |
818 |
* Inserts all of the elements in the specified collection into this |
819 |
* list, starting at the specified position. Shifts the element |
820 |
* currently at that position (if any) and any subsequent elements to |
821 |
* the right (increases their indices). The new elements will appear |
822 |
* in this list in the order that they are returned by the |
823 |
* specified collection's iterator. |
824 |
* |
825 |
* @param index index at which to insert the first element |
826 |
* from the specified collection |
827 |
* @param c collection containing elements to be added to this list |
828 |
* @return {@code true} if this list changed as a result of the call |
829 |
* @throws IndexOutOfBoundsException {@inheritDoc} |
830 |
* @throws NullPointerException if the specified collection is null |
831 |
* @see #add(int,Object) |
832 |
*/ |
833 |
public boolean addAll(int index, Collection<? extends E> c) { |
834 |
Object[] cs = c.toArray(); |
835 |
final ReentrantLock lock = this.lock; |
836 |
lock.lock(); |
837 |
try { |
838 |
Object[] elements = getArray(); |
839 |
int len = elements.length; |
840 |
if (index > len || index < 0) |
841 |
throw new IndexOutOfBoundsException("Index: "+index+ |
842 |
", Size: "+len); |
843 |
if (cs.length == 0) |
844 |
return false; |
845 |
int numMoved = len - index; |
846 |
Object[] newElements; |
847 |
if (numMoved == 0) |
848 |
newElements = Arrays.copyOf(elements, len + cs.length); |
849 |
else { |
850 |
newElements = new Object[len + cs.length]; |
851 |
System.arraycopy(elements, 0, newElements, 0, index); |
852 |
System.arraycopy(elements, index, |
853 |
newElements, index + cs.length, |
854 |
numMoved); |
855 |
} |
856 |
System.arraycopy(cs, 0, newElements, index, cs.length); |
857 |
setArray(newElements); |
858 |
return true; |
859 |
} finally { |
860 |
lock.unlock(); |
861 |
} |
862 |
} |
863 |
|
864 |
public void forEach(Consumer<? super E> action) { |
865 |
if (action == null) throw new NullPointerException(); |
866 |
Object[] elements = getArray(); |
867 |
int len = elements.length; |
868 |
for (int i = 0; i < len; ++i) { |
869 |
@SuppressWarnings("unchecked") E e = (E) elements[i]; |
870 |
action.accept(e); |
871 |
} |
872 |
} |
873 |
|
874 |
public boolean removeIf(Predicate<? super E> filter) { |
875 |
if (filter == null) throw new NullPointerException(); |
876 |
final ReentrantLock lock = this.lock; |
877 |
lock.lock(); |
878 |
try { |
879 |
Object[] elements = getArray(); |
880 |
int len = elements.length; |
881 |
if (len != 0) { |
882 |
int newlen = 0; |
883 |
Object[] temp = new Object[len]; |
884 |
for (int i = 0; i < len; ++i) { |
885 |
@SuppressWarnings("unchecked") E e = (E) elements[i]; |
886 |
if (!filter.test(e)) |
887 |
temp[newlen++] = e; |
888 |
} |
889 |
if (newlen != len) { |
890 |
setArray(Arrays.copyOf(temp, newlen)); |
891 |
return true; |
892 |
} |
893 |
} |
894 |
return false; |
895 |
} finally { |
896 |
lock.unlock(); |
897 |
} |
898 |
} |
899 |
|
900 |
public void replaceAll(UnaryOperator<E> operator) { |
901 |
if (operator == null) throw new NullPointerException(); |
902 |
final ReentrantLock lock = this.lock; |
903 |
lock.lock(); |
904 |
try { |
905 |
Object[] elements = getArray(); |
906 |
int len = elements.length; |
907 |
Object[] newElements = Arrays.copyOf(elements, len); |
908 |
for (int i = 0; i < len; ++i) { |
909 |
@SuppressWarnings("unchecked") E e = (E) elements[i]; |
910 |
newElements[i] = operator.apply(e); |
911 |
} |
912 |
setArray(newElements); |
913 |
} finally { |
914 |
lock.unlock(); |
915 |
} |
916 |
} |
917 |
|
918 |
public void sort(Comparator<? super E> c) { |
919 |
final ReentrantLock lock = this.lock; |
920 |
lock.lock(); |
921 |
try { |
922 |
Object[] elements = getArray(); |
923 |
Object[] newElements = Arrays.copyOf(elements, elements.length); |
924 |
@SuppressWarnings("unchecked") E[] es = (E[])newElements; |
925 |
Arrays.sort(es, c); |
926 |
setArray(newElements); |
927 |
} finally { |
928 |
lock.unlock(); |
929 |
} |
930 |
} |
931 |
|
932 |
/** |
933 |
* Saves this list to a stream (that is, serializes it). |
934 |
* |
935 |
* @param s the stream |
936 |
* @throws java.io.IOException if an I/O error occurs |
937 |
* @serialData The length of the array backing the list is emitted |
938 |
* (int), followed by all of its elements (each an Object) |
939 |
* in the proper order. |
940 |
*/ |
941 |
private void writeObject(java.io.ObjectOutputStream s) |
942 |
throws java.io.IOException { |
943 |
|
944 |
s.defaultWriteObject(); |
945 |
|
946 |
Object[] elements = getArray(); |
947 |
// Write out array length |
948 |
s.writeInt(elements.length); |
949 |
|
950 |
// Write out all elements in the proper order. |
951 |
for (Object element : elements) |
952 |
s.writeObject(element); |
953 |
} |
954 |
|
955 |
/** |
956 |
* Reconstitutes this list from a stream (that is, deserializes it). |
957 |
* @param s the stream |
958 |
* @throws ClassNotFoundException if the class of a serialized object |
959 |
* could not be found |
960 |
* @throws java.io.IOException if an I/O error occurs |
961 |
*/ |
962 |
private void readObject(java.io.ObjectInputStream s) |
963 |
throws java.io.IOException, ClassNotFoundException { |
964 |
|
965 |
s.defaultReadObject(); |
966 |
|
967 |
// bind to new lock |
968 |
resetLock(); |
969 |
|
970 |
// Read in array length and allocate array |
971 |
int len = s.readInt(); |
972 |
Object[] elements = new Object[len]; |
973 |
|
974 |
// Read in all elements in the proper order. |
975 |
for (int i = 0; i < len; i++) |
976 |
elements[i] = s.readObject(); |
977 |
setArray(elements); |
978 |
} |
979 |
|
980 |
/** |
981 |
* Returns a string representation of this list. The string |
982 |
* representation consists of the string representations of the list's |
983 |
* elements in the order they are returned by its iterator, enclosed in |
984 |
* square brackets ({@code "[]"}). Adjacent elements are separated by |
985 |
* the characters {@code ", "} (comma and space). Elements are |
986 |
* converted to strings as by {@link String#valueOf(Object)}. |
987 |
* |
988 |
* @return a string representation of this list |
989 |
*/ |
990 |
public String toString() { |
991 |
return Arrays.toString(getArray()); |
992 |
} |
993 |
|
994 |
/** |
995 |
* Compares the specified object with this list for equality. |
996 |
* Returns {@code true} if the specified object is the same object |
997 |
* as this object, or if it is also a {@link List} and the sequence |
998 |
* of elements returned by an {@linkplain List#iterator() iterator} |
999 |
* over the specified list is the same as the sequence returned by |
1000 |
* an iterator over this list. The two sequences are considered to |
1001 |
* be the same if they have the same length and corresponding |
1002 |
* elements at the same position in the sequence are <em>equal</em>. |
1003 |
* Two elements {@code e1} and {@code e2} are considered |
1004 |
* <em>equal</em> if {@code Objects.equals(e1, e2)}. |
1005 |
* |
1006 |
* @param o the object to be compared for equality with this list |
1007 |
* @return {@code true} if the specified object is equal to this list |
1008 |
*/ |
1009 |
public boolean equals(Object o) { |
1010 |
if (o == this) |
1011 |
return true; |
1012 |
if (!(o instanceof List)) |
1013 |
return false; |
1014 |
|
1015 |
List<?> list = (List<?>)(o); |
1016 |
Iterator<?> it = list.iterator(); |
1017 |
Object[] elements = getArray(); |
1018 |
int len = elements.length; |
1019 |
for (int i = 0; i < len; ++i) |
1020 |
if (!it.hasNext() || !eq(elements[i], it.next())) |
1021 |
return false; |
1022 |
if (it.hasNext()) |
1023 |
return false; |
1024 |
return true; |
1025 |
} |
1026 |
|
1027 |
/** |
1028 |
* Returns the hash code value for this list. |
1029 |
* |
1030 |
* <p>This implementation uses the definition in {@link List#hashCode}. |
1031 |
* |
1032 |
* @return the hash code value for this list |
1033 |
*/ |
1034 |
public int hashCode() { |
1035 |
int hashCode = 1; |
1036 |
Object[] elements = getArray(); |
1037 |
int len = elements.length; |
1038 |
for (int i = 0; i < len; ++i) { |
1039 |
Object obj = elements[i]; |
1040 |
hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode()); |
1041 |
} |
1042 |
return hashCode; |
1043 |
} |
1044 |
|
1045 |
/** |
1046 |
* Returns an iterator over the elements in this list in proper sequence. |
1047 |
* |
1048 |
* <p>The returned iterator provides a snapshot of the state of the list |
1049 |
* when the iterator was constructed. No synchronization is needed while |
1050 |
* traversing the iterator. The iterator does <em>NOT</em> support the |
1051 |
* {@code remove} method. |
1052 |
* |
1053 |
* @return an iterator over the elements in this list in proper sequence |
1054 |
*/ |
1055 |
public Iterator<E> iterator() { |
1056 |
return new COWIterator<E>(getArray(), 0); |
1057 |
} |
1058 |
|
1059 |
/** |
1060 |
* {@inheritDoc} |
1061 |
* |
1062 |
* <p>The returned iterator provides a snapshot of the state of the list |
1063 |
* when the iterator was constructed. No synchronization is needed while |
1064 |
* traversing the iterator. The iterator does <em>NOT</em> support the |
1065 |
* {@code remove}, {@code set} or {@code add} methods. |
1066 |
*/ |
1067 |
public ListIterator<E> listIterator() { |
1068 |
return new COWIterator<E>(getArray(), 0); |
1069 |
} |
1070 |
|
1071 |
/** |
1072 |
* {@inheritDoc} |
1073 |
* |
1074 |
* <p>The returned iterator provides a snapshot of the state of the list |
1075 |
* when the iterator was constructed. No synchronization is needed while |
1076 |
* traversing the iterator. The iterator does <em>NOT</em> support the |
1077 |
* {@code remove}, {@code set} or {@code add} methods. |
1078 |
* |
1079 |
* @throws IndexOutOfBoundsException {@inheritDoc} |
1080 |
*/ |
1081 |
public ListIterator<E> listIterator(int index) { |
1082 |
Object[] elements = getArray(); |
1083 |
int len = elements.length; |
1084 |
if (index < 0 || index > len) |
1085 |
throw new IndexOutOfBoundsException("Index: "+index); |
1086 |
|
1087 |
return new COWIterator<E>(elements, index); |
1088 |
} |
1089 |
|
1090 |
/** |
1091 |
* Returns a {@link Spliterator} over the elements in this list. |
1092 |
* |
1093 |
* <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE}, |
1094 |
* {@link Spliterator#ORDERED}, {@link Spliterator#SIZED}, and |
1095 |
* {@link Spliterator#SUBSIZED}. |
1096 |
* |
1097 |
* <p>The spliterator provides a snapshot of the state of the list |
1098 |
* when the spliterator was constructed. No synchronization is needed while |
1099 |
* operating on the spliterator. The spliterator does <em>NOT</em> support |
1100 |
* the {@code remove}, {@code set} or {@code add} methods. |
1101 |
* |
1102 |
* @return a {@code Spliterator} over the elements in this list |
1103 |
* @since 1.8 |
1104 |
*/ |
1105 |
public Spliterator<E> spliterator() { |
1106 |
return Spliterators.spliterator |
1107 |
(getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED); |
1108 |
} |
1109 |
|
1110 |
static final class COWIterator<E> implements ListIterator<E> { |
1111 |
/** Snapshot of the array */ |
1112 |
private final Object[] snapshot; |
1113 |
/** Index of element to be returned by subsequent call to next. */ |
1114 |
private int cursor; |
1115 |
|
1116 |
private COWIterator(Object[] elements, int initialCursor) { |
1117 |
cursor = initialCursor; |
1118 |
snapshot = elements; |
1119 |
} |
1120 |
|
1121 |
public boolean hasNext() { |
1122 |
return cursor < snapshot.length; |
1123 |
} |
1124 |
|
1125 |
public boolean hasPrevious() { |
1126 |
return cursor > 0; |
1127 |
} |
1128 |
|
1129 |
@SuppressWarnings("unchecked") |
1130 |
public E next() { |
1131 |
if (! hasNext()) |
1132 |
throw new NoSuchElementException(); |
1133 |
return (E) snapshot[cursor++]; |
1134 |
} |
1135 |
|
1136 |
@SuppressWarnings("unchecked") |
1137 |
public E previous() { |
1138 |
if (! hasPrevious()) |
1139 |
throw new NoSuchElementException(); |
1140 |
return (E) snapshot[--cursor]; |
1141 |
} |
1142 |
|
1143 |
public int nextIndex() { |
1144 |
return cursor; |
1145 |
} |
1146 |
|
1147 |
public int previousIndex() { |
1148 |
return cursor-1; |
1149 |
} |
1150 |
|
1151 |
/** |
1152 |
* Not supported. Always throws UnsupportedOperationException. |
1153 |
* @throws UnsupportedOperationException always; {@code remove} |
1154 |
* is not supported by this iterator. |
1155 |
*/ |
1156 |
public void remove() { |
1157 |
throw new UnsupportedOperationException(); |
1158 |
} |
1159 |
|
1160 |
/** |
1161 |
* Not supported. Always throws UnsupportedOperationException. |
1162 |
* @throws UnsupportedOperationException always; {@code set} |
1163 |
* is not supported by this iterator. |
1164 |
*/ |
1165 |
public void set(E e) { |
1166 |
throw new UnsupportedOperationException(); |
1167 |
} |
1168 |
|
1169 |
/** |
1170 |
* Not supported. Always throws UnsupportedOperationException. |
1171 |
* @throws UnsupportedOperationException always; {@code add} |
1172 |
* is not supported by this iterator. |
1173 |
*/ |
1174 |
public void add(E e) { |
1175 |
throw new UnsupportedOperationException(); |
1176 |
} |
1177 |
} |
1178 |
|
1179 |
/** |
1180 |
* Returns a view of the portion of this list between |
1181 |
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. |
1182 |
* The returned list is backed by this list, so changes in the |
1183 |
* returned list are reflected in this list. |
1184 |
* |
1185 |
* <p>The semantics of the list returned by this method become |
1186 |
* undefined if the backing list (i.e., this list) is modified in |
1187 |
* any way other than via the returned list. |
1188 |
* |
1189 |
* @param fromIndex low endpoint (inclusive) of the subList |
1190 |
* @param toIndex high endpoint (exclusive) of the subList |
1191 |
* @return a view of the specified range within this list |
1192 |
* @throws IndexOutOfBoundsException {@inheritDoc} |
1193 |
*/ |
1194 |
public List<E> subList(int fromIndex, int toIndex) { |
1195 |
final ReentrantLock lock = this.lock; |
1196 |
lock.lock(); |
1197 |
try { |
1198 |
Object[] elements = getArray(); |
1199 |
int len = elements.length; |
1200 |
if (fromIndex < 0 || toIndex > len || fromIndex > toIndex) |
1201 |
throw new IndexOutOfBoundsException(); |
1202 |
return new COWSubList<E>(this, fromIndex, toIndex); |
1203 |
} finally { |
1204 |
lock.unlock(); |
1205 |
} |
1206 |
} |
1207 |
|
1208 |
/** |
1209 |
* Sublist for CopyOnWriteArrayList. |
1210 |
* This class extends AbstractList merely for convenience, to |
1211 |
* avoid having to define addAll, etc. This doesn't hurt, but |
1212 |
* is wasteful. This class does not need or use modCount |
1213 |
* mechanics in AbstractList, but does need to check for |
1214 |
* concurrent modification using similar mechanics. On each |
1215 |
* operation, the array that we expect the backing list to use |
1216 |
* is checked and updated. Since we do this for all of the |
1217 |
* base operations invoked by those defined in AbstractList, |
1218 |
* all is well. While inefficient, this is not worth |
1219 |
* improving. The kinds of list operations inherited from |
1220 |
* AbstractList are already so slow on COW sublists that |
1221 |
* adding a bit more space/time doesn't seem even noticeable. |
1222 |
*/ |
1223 |
private static class COWSubList<E> |
1224 |
extends AbstractList<E> |
1225 |
implements RandomAccess |
1226 |
{ |
1227 |
private final CopyOnWriteArrayList<E> l; |
1228 |
private final int offset; |
1229 |
private int size; |
1230 |
private Object[] expectedArray; |
1231 |
|
1232 |
// only call this holding l's lock |
1233 |
COWSubList(CopyOnWriteArrayList<E> list, |
1234 |
int fromIndex, int toIndex) { |
1235 |
l = list; |
1236 |
expectedArray = l.getArray(); |
1237 |
offset = fromIndex; |
1238 |
size = toIndex - fromIndex; |
1239 |
} |
1240 |
|
1241 |
// only call this holding l's lock |
1242 |
private void checkForComodification() { |
1243 |
if (l.getArray() != expectedArray) |
1244 |
throw new ConcurrentModificationException(); |
1245 |
} |
1246 |
|
1247 |
// only call this holding l's lock |
1248 |
private void rangeCheck(int index) { |
1249 |
if (index < 0 || index >= size) |
1250 |
throw new IndexOutOfBoundsException("Index: "+index+ |
1251 |
",Size: "+size); |
1252 |
} |
1253 |
|
1254 |
public E set(int index, E element) { |
1255 |
final ReentrantLock lock = l.lock; |
1256 |
lock.lock(); |
1257 |
try { |
1258 |
rangeCheck(index); |
1259 |
checkForComodification(); |
1260 |
E x = l.set(index+offset, element); |
1261 |
expectedArray = l.getArray(); |
1262 |
return x; |
1263 |
} finally { |
1264 |
lock.unlock(); |
1265 |
} |
1266 |
} |
1267 |
|
1268 |
public E get(int index) { |
1269 |
final ReentrantLock lock = l.lock; |
1270 |
lock.lock(); |
1271 |
try { |
1272 |
rangeCheck(index); |
1273 |
checkForComodification(); |
1274 |
return l.get(index+offset); |
1275 |
} finally { |
1276 |
lock.unlock(); |
1277 |
} |
1278 |
} |
1279 |
|
1280 |
public int size() { |
1281 |
final ReentrantLock lock = l.lock; |
1282 |
lock.lock(); |
1283 |
try { |
1284 |
checkForComodification(); |
1285 |
return size; |
1286 |
} finally { |
1287 |
lock.unlock(); |
1288 |
} |
1289 |
} |
1290 |
|
1291 |
public void add(int index, E element) { |
1292 |
final ReentrantLock lock = l.lock; |
1293 |
lock.lock(); |
1294 |
try { |
1295 |
checkForComodification(); |
1296 |
if (index < 0 || index > size) |
1297 |
throw new IndexOutOfBoundsException(); |
1298 |
l.add(index+offset, element); |
1299 |
expectedArray = l.getArray(); |
1300 |
size++; |
1301 |
} finally { |
1302 |
lock.unlock(); |
1303 |
} |
1304 |
} |
1305 |
|
1306 |
public void clear() { |
1307 |
final ReentrantLock lock = l.lock; |
1308 |
lock.lock(); |
1309 |
try { |
1310 |
checkForComodification(); |
1311 |
l.removeRange(offset, offset+size); |
1312 |
expectedArray = l.getArray(); |
1313 |
size = 0; |
1314 |
} finally { |
1315 |
lock.unlock(); |
1316 |
} |
1317 |
} |
1318 |
|
1319 |
public E remove(int index) { |
1320 |
final ReentrantLock lock = l.lock; |
1321 |
lock.lock(); |
1322 |
try { |
1323 |
rangeCheck(index); |
1324 |
checkForComodification(); |
1325 |
E result = l.remove(index+offset); |
1326 |
expectedArray = l.getArray(); |
1327 |
size--; |
1328 |
return result; |
1329 |
} finally { |
1330 |
lock.unlock(); |
1331 |
} |
1332 |
} |
1333 |
|
1334 |
public boolean remove(Object o) { |
1335 |
int index = indexOf(o); |
1336 |
if (index == -1) |
1337 |
return false; |
1338 |
remove(index); |
1339 |
return true; |
1340 |
} |
1341 |
|
1342 |
public Iterator<E> iterator() { |
1343 |
final ReentrantLock lock = l.lock; |
1344 |
lock.lock(); |
1345 |
try { |
1346 |
checkForComodification(); |
1347 |
return new COWSubListIterator<E>(l, 0, offset, size); |
1348 |
} finally { |
1349 |
lock.unlock(); |
1350 |
} |
1351 |
} |
1352 |
|
1353 |
public ListIterator<E> listIterator(int index) { |
1354 |
final ReentrantLock lock = l.lock; |
1355 |
lock.lock(); |
1356 |
try { |
1357 |
checkForComodification(); |
1358 |
if (index < 0 || index > size) |
1359 |
throw new IndexOutOfBoundsException("Index: "+index+ |
1360 |
", Size: "+size); |
1361 |
return new COWSubListIterator<E>(l, index, offset, size); |
1362 |
} finally { |
1363 |
lock.unlock(); |
1364 |
} |
1365 |
} |
1366 |
|
1367 |
public List<E> subList(int fromIndex, int toIndex) { |
1368 |
final ReentrantLock lock = l.lock; |
1369 |
lock.lock(); |
1370 |
try { |
1371 |
checkForComodification(); |
1372 |
if (fromIndex < 0 || toIndex > size || fromIndex > toIndex) |
1373 |
throw new IndexOutOfBoundsException(); |
1374 |
return new COWSubList<E>(l, fromIndex + offset, |
1375 |
toIndex + offset); |
1376 |
} finally { |
1377 |
lock.unlock(); |
1378 |
} |
1379 |
} |
1380 |
|
1381 |
public void forEach(Consumer<? super E> action) { |
1382 |
if (action == null) throw new NullPointerException(); |
1383 |
int lo = offset; |
1384 |
int hi = offset + size; |
1385 |
Object[] a = expectedArray; |
1386 |
if (l.getArray() != a) |
1387 |
throw new ConcurrentModificationException(); |
1388 |
if (lo < 0 || hi > a.length) |
1389 |
throw new IndexOutOfBoundsException(); |
1390 |
for (int i = lo; i < hi; ++i) { |
1391 |
@SuppressWarnings("unchecked") E e = (E) a[i]; |
1392 |
action.accept(e); |
1393 |
} |
1394 |
} |
1395 |
|
1396 |
public void replaceAll(UnaryOperator<E> operator) { |
1397 |
if (operator == null) throw new NullPointerException(); |
1398 |
final ReentrantLock lock = l.lock; |
1399 |
lock.lock(); |
1400 |
try { |
1401 |
int lo = offset; |
1402 |
int hi = offset + size; |
1403 |
Object[] elements = expectedArray; |
1404 |
if (l.getArray() != elements) |
1405 |
throw new ConcurrentModificationException(); |
1406 |
int len = elements.length; |
1407 |
if (lo < 0 || hi > len) |
1408 |
throw new IndexOutOfBoundsException(); |
1409 |
Object[] newElements = Arrays.copyOf(elements, len); |
1410 |
for (int i = lo; i < hi; ++i) { |
1411 |
@SuppressWarnings("unchecked") E e = (E) elements[i]; |
1412 |
newElements[i] = operator.apply(e); |
1413 |
} |
1414 |
l.setArray(expectedArray = newElements); |
1415 |
} finally { |
1416 |
lock.unlock(); |
1417 |
} |
1418 |
} |
1419 |
|
1420 |
public void sort(Comparator<? super E> c) { |
1421 |
final ReentrantLock lock = l.lock; |
1422 |
lock.lock(); |
1423 |
try { |
1424 |
int lo = offset; |
1425 |
int hi = offset + size; |
1426 |
Object[] elements = expectedArray; |
1427 |
if (l.getArray() != elements) |
1428 |
throw new ConcurrentModificationException(); |
1429 |
int len = elements.length; |
1430 |
if (lo < 0 || hi > len) |
1431 |
throw new IndexOutOfBoundsException(); |
1432 |
Object[] newElements = Arrays.copyOf(elements, len); |
1433 |
@SuppressWarnings("unchecked") E[] es = (E[])newElements; |
1434 |
Arrays.sort(es, lo, hi, c); |
1435 |
l.setArray(expectedArray = newElements); |
1436 |
} finally { |
1437 |
lock.unlock(); |
1438 |
} |
1439 |
} |
1440 |
|
1441 |
public boolean removeAll(Collection<?> c) { |
1442 |
if (c == null) throw new NullPointerException(); |
1443 |
boolean removed = false; |
1444 |
final ReentrantLock lock = l.lock; |
1445 |
lock.lock(); |
1446 |
try { |
1447 |
int n = size; |
1448 |
if (n > 0) { |
1449 |
int lo = offset; |
1450 |
int hi = offset + n; |
1451 |
Object[] elements = expectedArray; |
1452 |
if (l.getArray() != elements) |
1453 |
throw new ConcurrentModificationException(); |
1454 |
int len = elements.length; |
1455 |
if (lo < 0 || hi > len) |
1456 |
throw new IndexOutOfBoundsException(); |
1457 |
int newSize = 0; |
1458 |
Object[] temp = new Object[n]; |
1459 |
for (int i = lo; i < hi; ++i) { |
1460 |
Object element = elements[i]; |
1461 |
if (!c.contains(element)) |
1462 |
temp[newSize++] = element; |
1463 |
} |
1464 |
if (newSize != n) { |
1465 |
Object[] newElements = new Object[len - n + newSize]; |
1466 |
System.arraycopy(elements, 0, newElements, 0, lo); |
1467 |
System.arraycopy(temp, 0, newElements, lo, newSize); |
1468 |
System.arraycopy(elements, hi, newElements, |
1469 |
lo + newSize, len - hi); |
1470 |
size = newSize; |
1471 |
removed = true; |
1472 |
l.setArray(expectedArray = newElements); |
1473 |
} |
1474 |
} |
1475 |
} finally { |
1476 |
lock.unlock(); |
1477 |
} |
1478 |
return removed; |
1479 |
} |
1480 |
|
1481 |
public boolean retainAll(Collection<?> c) { |
1482 |
if (c == null) throw new NullPointerException(); |
1483 |
boolean removed = false; |
1484 |
final ReentrantLock lock = l.lock; |
1485 |
lock.lock(); |
1486 |
try { |
1487 |
int n = size; |
1488 |
if (n > 0) { |
1489 |
int lo = offset; |
1490 |
int hi = offset + n; |
1491 |
Object[] elements = expectedArray; |
1492 |
if (l.getArray() != elements) |
1493 |
throw new ConcurrentModificationException(); |
1494 |
int len = elements.length; |
1495 |
if (lo < 0 || hi > len) |
1496 |
throw new IndexOutOfBoundsException(); |
1497 |
int newSize = 0; |
1498 |
Object[] temp = new Object[n]; |
1499 |
for (int i = lo; i < hi; ++i) { |
1500 |
Object element = elements[i]; |
1501 |
if (c.contains(element)) |
1502 |
temp[newSize++] = element; |
1503 |
} |
1504 |
if (newSize != n) { |
1505 |
Object[] newElements = new Object[len - n + newSize]; |
1506 |
System.arraycopy(elements, 0, newElements, 0, lo); |
1507 |
System.arraycopy(temp, 0, newElements, lo, newSize); |
1508 |
System.arraycopy(elements, hi, newElements, |
1509 |
lo + newSize, len - hi); |
1510 |
size = newSize; |
1511 |
removed = true; |
1512 |
l.setArray(expectedArray = newElements); |
1513 |
} |
1514 |
} |
1515 |
} finally { |
1516 |
lock.unlock(); |
1517 |
} |
1518 |
return removed; |
1519 |
} |
1520 |
|
1521 |
public boolean removeIf(Predicate<? super E> filter) { |
1522 |
if (filter == null) throw new NullPointerException(); |
1523 |
boolean removed = false; |
1524 |
final ReentrantLock lock = l.lock; |
1525 |
lock.lock(); |
1526 |
try { |
1527 |
int n = size; |
1528 |
if (n > 0) { |
1529 |
int lo = offset; |
1530 |
int hi = offset + n; |
1531 |
Object[] elements = expectedArray; |
1532 |
if (l.getArray() != elements) |
1533 |
throw new ConcurrentModificationException(); |
1534 |
int len = elements.length; |
1535 |
if (lo < 0 || hi > len) |
1536 |
throw new IndexOutOfBoundsException(); |
1537 |
int newSize = 0; |
1538 |
Object[] temp = new Object[n]; |
1539 |
for (int i = lo; i < hi; ++i) { |
1540 |
@SuppressWarnings("unchecked") E e = (E) elements[i]; |
1541 |
if (!filter.test(e)) |
1542 |
temp[newSize++] = e; |
1543 |
} |
1544 |
if (newSize != n) { |
1545 |
Object[] newElements = new Object[len - n + newSize]; |
1546 |
System.arraycopy(elements, 0, newElements, 0, lo); |
1547 |
System.arraycopy(temp, 0, newElements, lo, newSize); |
1548 |
System.arraycopy(elements, hi, newElements, |
1549 |
lo + newSize, len - hi); |
1550 |
size = newSize; |
1551 |
removed = true; |
1552 |
l.setArray(expectedArray = newElements); |
1553 |
} |
1554 |
} |
1555 |
} finally { |
1556 |
lock.unlock(); |
1557 |
} |
1558 |
return removed; |
1559 |
} |
1560 |
|
1561 |
public Spliterator<E> spliterator() { |
1562 |
int lo = offset; |
1563 |
int hi = offset + size; |
1564 |
Object[] a = expectedArray; |
1565 |
if (l.getArray() != a) |
1566 |
throw new ConcurrentModificationException(); |
1567 |
if (lo < 0 || hi > a.length) |
1568 |
throw new IndexOutOfBoundsException(); |
1569 |
return Spliterators.spliterator |
1570 |
(a, lo, hi, Spliterator.IMMUTABLE | Spliterator.ORDERED); |
1571 |
} |
1572 |
|
1573 |
} |
1574 |
|
1575 |
private static class COWSubListIterator<E> implements ListIterator<E> { |
1576 |
private final ListIterator<E> it; |
1577 |
private final int offset; |
1578 |
private final int size; |
1579 |
|
1580 |
COWSubListIterator(List<E> l, int index, int offset, int size) { |
1581 |
this.offset = offset; |
1582 |
this.size = size; |
1583 |
it = l.listIterator(index+offset); |
1584 |
} |
1585 |
|
1586 |
public boolean hasNext() { |
1587 |
return nextIndex() < size; |
1588 |
} |
1589 |
|
1590 |
public E next() { |
1591 |
if (hasNext()) |
1592 |
return it.next(); |
1593 |
else |
1594 |
throw new NoSuchElementException(); |
1595 |
} |
1596 |
|
1597 |
public boolean hasPrevious() { |
1598 |
return previousIndex() >= 0; |
1599 |
} |
1600 |
|
1601 |
public E previous() { |
1602 |
if (hasPrevious()) |
1603 |
return it.previous(); |
1604 |
else |
1605 |
throw new NoSuchElementException(); |
1606 |
} |
1607 |
|
1608 |
public int nextIndex() { |
1609 |
return it.nextIndex() - offset; |
1610 |
} |
1611 |
|
1612 |
public int previousIndex() { |
1613 |
return it.previousIndex() - offset; |
1614 |
} |
1615 |
|
1616 |
public void remove() { |
1617 |
throw new UnsupportedOperationException(); |
1618 |
} |
1619 |
|
1620 |
public void set(E e) { |
1621 |
throw new UnsupportedOperationException(); |
1622 |
} |
1623 |
|
1624 |
public void add(E e) { |
1625 |
throw new UnsupportedOperationException(); |
1626 |
} |
1627 |
} |
1628 |
|
1629 |
// Support for resetting lock while deserializing |
1630 |
private void resetLock() { |
1631 |
UNSAFE.putObjectVolatile(this, lockOffset, new ReentrantLock()); |
1632 |
} |
1633 |
private static final sun.misc.Unsafe UNSAFE; |
1634 |
private static final long lockOffset; |
1635 |
static { |
1636 |
try { |
1637 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
1638 |
Class<?> k = CopyOnWriteArrayList.class; |
1639 |
lockOffset = UNSAFE.objectFieldOffset |
1640 |
(k.getDeclaredField("lock")); |
1641 |
} catch (Exception e) { |
1642 |
throw new Error(e); |
1643 |
} |
1644 |
} |
1645 |
} |