5 |
|
* http://creativecommons.org/publicdomain/zero/1.0/ |
6 |
|
*/ |
7 |
|
|
8 |
+ |
import static java.util.concurrent.TimeUnit.HOURS; |
9 |
|
import static java.util.concurrent.TimeUnit.MILLISECONDS; |
10 |
|
|
11 |
+ |
import java.util.ArrayDeque; |
12 |
|
import java.util.ArrayList; |
13 |
+ |
import java.util.Arrays; |
14 |
|
import java.util.Collection; |
15 |
|
import java.util.Collections; |
16 |
+ |
import java.util.ConcurrentModificationException; |
17 |
|
import java.util.Deque; |
18 |
|
import java.util.HashSet; |
19 |
|
import java.util.Iterator; |
20 |
|
import java.util.List; |
21 |
|
import java.util.NoSuchElementException; |
22 |
|
import java.util.Queue; |
23 |
+ |
import java.util.Set; |
24 |
|
import java.util.Spliterator; |
25 |
+ |
import java.util.concurrent.BlockingDeque; |
26 |
+ |
import java.util.concurrent.BlockingQueue; |
27 |
+ |
import java.util.concurrent.ConcurrentLinkedQueue; |
28 |
|
import java.util.concurrent.CountDownLatch; |
29 |
|
import java.util.concurrent.Executors; |
30 |
|
import java.util.concurrent.ExecutorService; |
31 |
|
import java.util.concurrent.Future; |
32 |
+ |
import java.util.concurrent.Phaser; |
33 |
|
import java.util.concurrent.ThreadLocalRandom; |
34 |
|
import java.util.concurrent.atomic.AtomicBoolean; |
35 |
|
import java.util.concurrent.atomic.AtomicLong; |
36 |
|
import java.util.concurrent.atomic.AtomicReference; |
37 |
|
import java.util.function.Consumer; |
38 |
|
import java.util.function.Predicate; |
39 |
+ |
import java.util.stream.Collectors; |
40 |
|
|
41 |
|
import junit.framework.Test; |
42 |
|
|
61 |
|
|
62 |
|
Object bomb() { |
63 |
|
return new Object() { |
64 |
< |
public boolean equals(Object x) { throw new AssertionError(); } |
65 |
< |
public int hashCode() { throw new AssertionError(); } |
66 |
< |
}; |
64 |
> |
@Override public boolean equals(Object x) { throw new AssertionError(); } |
65 |
> |
@Override public int hashCode() { throw new AssertionError(); } |
66 |
> |
@Override public String toString() { throw new AssertionError(); } |
67 |
> |
}; |
68 |
|
} |
69 |
|
|
70 |
|
/** Checks properties of empty collections. */ |
71 |
< |
public void testEmptyMeansEmpty() { |
71 |
> |
public void testEmptyMeansEmpty() throws Throwable { |
72 |
|
Collection c = impl.emptyCollection(); |
73 |
|
emptyMeansEmpty(c); |
74 |
|
|
75 |
< |
if (c instanceof java.io.Serializable) |
76 |
< |
emptyMeansEmpty(serialClone(c)); |
75 |
> |
if (c instanceof java.io.Serializable) { |
76 |
> |
try { |
77 |
> |
emptyMeansEmpty(serialClonePossiblyFailing(c)); |
78 |
> |
} catch (java.io.NotSerializableException ex) { |
79 |
> |
// excusable when we have a serializable wrapper around |
80 |
> |
// a non-serializable collection, as can happen with: |
81 |
> |
// Vector.subList() => wrapped AbstractList$RandomAccessSubList |
82 |
> |
if (testImplementationDetails |
83 |
> |
&& (! c.getClass().getName().matches( |
84 |
> |
"java.util.Collections.*"))) |
85 |
> |
throw ex; |
86 |
> |
} |
87 |
> |
} |
88 |
|
|
89 |
|
Collection clone = cloneableClone(c); |
90 |
|
if (clone != null) |
91 |
|
emptyMeansEmpty(clone); |
92 |
|
} |
93 |
|
|
94 |
< |
void emptyMeansEmpty(Collection c) { |
94 |
> |
void emptyMeansEmpty(Collection c) throws InterruptedException { |
95 |
|
assertTrue(c.isEmpty()); |
96 |
|
assertEquals(0, c.size()); |
97 |
|
assertEquals("[]", c.toString()); |
98 |
+ |
if (c instanceof List<?>) { |
99 |
+ |
List x = (List) c; |
100 |
+ |
assertEquals(1, x.hashCode()); |
101 |
+ |
assertEquals(x, Collections.emptyList()); |
102 |
+ |
assertEquals(Collections.emptyList(), x); |
103 |
+ |
assertEquals(-1, x.indexOf(impl.makeElement(86))); |
104 |
+ |
assertEquals(-1, x.lastIndexOf(impl.makeElement(99))); |
105 |
+ |
assertThrows( |
106 |
+ |
IndexOutOfBoundsException.class, |
107 |
+ |
() -> x.get(0), |
108 |
+ |
() -> x.set(0, impl.makeElement(42))); |
109 |
+ |
} |
110 |
+ |
else if (c instanceof Set<?>) { |
111 |
+ |
assertEquals(0, c.hashCode()); |
112 |
+ |
assertEquals(c, Collections.emptySet()); |
113 |
+ |
assertEquals(Collections.emptySet(), c); |
114 |
+ |
} |
115 |
|
{ |
116 |
|
Object[] a = c.toArray(); |
117 |
|
assertEquals(0, a.length); |
133 |
|
assertSame(3, a[2]); |
134 |
|
} |
135 |
|
assertIteratorExhausted(c.iterator()); |
136 |
< |
Consumer alwaysThrows = (e) -> { throw new AssertionError(); }; |
136 |
> |
Consumer alwaysThrows = e -> { throw new AssertionError(); }; |
137 |
|
c.forEach(alwaysThrows); |
138 |
|
c.iterator().forEachRemaining(alwaysThrows); |
139 |
|
c.spliterator().forEachRemaining(alwaysThrows); |
158 |
|
assertFalse(d.removeFirstOccurrence(bomb())); |
159 |
|
assertFalse(d.removeLastOccurrence(bomb())); |
160 |
|
} |
161 |
+ |
if (c instanceof BlockingQueue) { |
162 |
+ |
BlockingQueue q = (BlockingQueue) c; |
163 |
+ |
assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit())); |
164 |
+ |
} |
165 |
+ |
if (c instanceof BlockingDeque) { |
166 |
+ |
BlockingDeque q = (BlockingDeque) c; |
167 |
+ |
assertNull(q.pollFirst(randomExpiredTimeout(), randomTimeUnit())); |
168 |
+ |
assertNull(q.pollLast(randomExpiredTimeout(), randomTimeUnit())); |
169 |
+ |
} |
170 |
|
} |
171 |
|
|
172 |
< |
public void testNullPointerExceptions() { |
172 |
> |
public void testNullPointerExceptions() throws InterruptedException { |
173 |
|
Collection c = impl.emptyCollection(); |
174 |
|
assertThrows( |
175 |
|
NullPointerException.class, |
189 |
|
NullPointerException.class, |
190 |
|
() -> c.add(null)); |
191 |
|
} |
192 |
< |
if (!impl.permitsNulls() |
145 |
< |
&& Queue.class.isAssignableFrom(impl.klazz())) { |
192 |
> |
if (!impl.permitsNulls() && c instanceof Queue) { |
193 |
|
Queue q = (Queue) c; |
194 |
|
assertThrows( |
195 |
|
NullPointerException.class, |
196 |
|
() -> q.offer(null)); |
197 |
|
} |
198 |
< |
if (!impl.permitsNulls() |
152 |
< |
&& Deque.class.isAssignableFrom(impl.klazz())) { |
198 |
> |
if (!impl.permitsNulls() && c instanceof Deque) { |
199 |
|
Deque d = (Deque) c; |
200 |
|
assertThrows( |
201 |
|
NullPointerException.class, |
206 |
|
() -> d.push(null), |
207 |
|
() -> d.descendingIterator().forEachRemaining(null)); |
208 |
|
} |
209 |
+ |
if (c instanceof BlockingQueue) { |
210 |
+ |
BlockingQueue q = (BlockingQueue) c; |
211 |
+ |
assertThrows( |
212 |
+ |
NullPointerException.class, |
213 |
+ |
() -> { |
214 |
+ |
try { q.offer(null, 1L, HOURS); } |
215 |
+ |
catch (InterruptedException ex) { |
216 |
+ |
throw new AssertionError(ex); |
217 |
+ |
}}, |
218 |
+ |
() -> { |
219 |
+ |
try { q.put(null); } |
220 |
+ |
catch (InterruptedException ex) { |
221 |
+ |
throw new AssertionError(ex); |
222 |
+ |
}}); |
223 |
+ |
} |
224 |
+ |
if (c instanceof BlockingDeque) { |
225 |
+ |
BlockingDeque q = (BlockingDeque) c; |
226 |
+ |
assertThrows( |
227 |
+ |
NullPointerException.class, |
228 |
+ |
() -> { |
229 |
+ |
try { q.offerFirst(null, 1L, HOURS); } |
230 |
+ |
catch (InterruptedException ex) { |
231 |
+ |
throw new AssertionError(ex); |
232 |
+ |
}}, |
233 |
+ |
() -> { |
234 |
+ |
try { q.offerLast(null, 1L, HOURS); } |
235 |
+ |
catch (InterruptedException ex) { |
236 |
+ |
throw new AssertionError(ex); |
237 |
+ |
}}, |
238 |
+ |
() -> { |
239 |
+ |
try { q.putFirst(null); } |
240 |
+ |
catch (InterruptedException ex) { |
241 |
+ |
throw new AssertionError(ex); |
242 |
+ |
}}, |
243 |
+ |
() -> { |
244 |
+ |
try { q.putLast(null); } |
245 |
+ |
catch (InterruptedException ex) { |
246 |
+ |
throw new AssertionError(ex); |
247 |
+ |
}}); |
248 |
+ |
} |
249 |
|
} |
250 |
|
|
251 |
|
public void testNoSuchElementExceptions() { |
254 |
|
NoSuchElementException.class, |
255 |
|
() -> c.iterator().next()); |
256 |
|
|
257 |
< |
if (Queue.class.isAssignableFrom(impl.klazz())) { |
257 |
> |
if (c instanceof Queue) { |
258 |
|
Queue q = (Queue) c; |
259 |
|
assertThrows( |
260 |
|
NoSuchElementException.class, |
261 |
|
() -> q.element(), |
262 |
|
() -> q.remove()); |
263 |
|
} |
264 |
< |
if (Deque.class.isAssignableFrom(impl.klazz())) { |
264 |
> |
if (c instanceof Deque) { |
265 |
|
Deque d = (Deque) c; |
266 |
|
assertThrows( |
267 |
|
NoSuchElementException.class, |
272 |
|
() -> d.pop(), |
273 |
|
() -> d.descendingIterator().next()); |
274 |
|
} |
275 |
+ |
if (c instanceof List) { |
276 |
+ |
List x = (List) c; |
277 |
+ |
assertThrows( |
278 |
+ |
NoSuchElementException.class, |
279 |
+ |
() -> x.iterator().next(), |
280 |
+ |
() -> x.listIterator().next(), |
281 |
+ |
() -> x.listIterator(0).next(), |
282 |
+ |
() -> x.listIterator().previous(), |
283 |
+ |
() -> x.listIterator(0).previous()); |
284 |
+ |
} |
285 |
|
} |
286 |
|
|
287 |
|
public void testRemoveIf() { |
288 |
|
Collection c = impl.emptyCollection(); |
289 |
+ |
boolean ordered = |
290 |
+ |
c.spliterator().hasCharacteristics(Spliterator.ORDERED); |
291 |
|
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
292 |
|
int n = rnd.nextInt(6); |
293 |
|
for (int i = 0; i < n; i++) c.add(impl.makeElement(i)); |
294 |
|
AtomicReference threwAt = new AtomicReference(null); |
295 |
< |
ArrayList survivors = new ArrayList(c); |
295 |
> |
List orig = rnd.nextBoolean() |
296 |
> |
? new ArrayList(c) |
297 |
> |
: Arrays.asList(c.toArray()); |
298 |
> |
|
299 |
> |
// Merely creating an iterator can change ArrayBlockingQueue behavior |
300 |
> |
Iterator it = rnd.nextBoolean() ? c.iterator() : null; |
301 |
> |
|
302 |
> |
ArrayList survivors = new ArrayList(); |
303 |
|
ArrayList accepts = new ArrayList(); |
304 |
|
ArrayList rejects = new ArrayList(); |
305 |
< |
Predicate randomPredicate = (e) -> { |
305 |
> |
|
306 |
> |
Predicate randomPredicate = e -> { |
307 |
|
assertNull(threwAt.get()); |
308 |
|
switch (rnd.nextInt(3)) { |
309 |
|
case 0: accepts.add(e); return true; |
313 |
|
} |
314 |
|
}; |
315 |
|
try { |
210 |
– |
assertFalse(survivors.contains(null)); |
316 |
|
try { |
317 |
|
boolean modified = c.removeIf(randomPredicate); |
318 |
< |
if (!modified) { |
319 |
< |
assertNull(threwAt.get()); |
320 |
< |
assertEquals(n, rejects.size()); |
321 |
< |
assertEquals(0, accepts.size()); |
318 |
> |
assertNull(threwAt.get()); |
319 |
> |
assertEquals(modified, accepts.size() > 0); |
320 |
> |
assertEquals(modified, rejects.size() != n); |
321 |
> |
assertEquals(accepts.size() + rejects.size(), n); |
322 |
> |
if (ordered) { |
323 |
> |
assertEquals(rejects, |
324 |
> |
Arrays.asList(c.toArray())); |
325 |
> |
} else { |
326 |
> |
assertEquals(new HashSet(rejects), |
327 |
> |
new HashSet(Arrays.asList(c.toArray()))); |
328 |
|
} |
329 |
< |
} catch (ArithmeticException ok) {} |
330 |
< |
survivors.removeAll(accepts); |
331 |
< |
assertEquals(n - accepts.size(), c.size()); |
329 |
> |
} catch (ArithmeticException ok) { |
330 |
> |
assertNotNull(threwAt.get()); |
331 |
> |
assertTrue(c.contains(threwAt.get())); |
332 |
> |
} |
333 |
> |
if (it != null && impl.isConcurrent()) |
334 |
> |
// check for weakly consistent iterator |
335 |
> |
while (it.hasNext()) assertTrue(orig.contains(it.next())); |
336 |
> |
switch (rnd.nextInt(4)) { |
337 |
> |
case 0: survivors.addAll(c); break; |
338 |
> |
case 1: survivors.addAll(Arrays.asList(c.toArray())); break; |
339 |
> |
case 2: c.forEach(survivors::add); break; |
340 |
> |
case 3: for (Object e : c) survivors.add(e); break; |
341 |
> |
} |
342 |
> |
assertTrue(orig.containsAll(accepts)); |
343 |
> |
assertTrue(orig.containsAll(rejects)); |
344 |
> |
assertTrue(orig.containsAll(survivors)); |
345 |
> |
assertTrue(orig.containsAll(c)); |
346 |
> |
assertTrue(c.containsAll(rejects)); |
347 |
|
assertTrue(c.containsAll(survivors)); |
348 |
|
assertTrue(survivors.containsAll(rejects)); |
349 |
< |
for (Object x : accepts) assertFalse(c.contains(x)); |
350 |
< |
if (threwAt.get() == null) |
351 |
< |
assertEquals(accepts.size() + rejects.size(), n); |
349 |
> |
if (threwAt.get() == null) { |
350 |
> |
assertEquals(n - accepts.size(), c.size()); |
351 |
> |
for (Object x : accepts) assertFalse(c.contains(x)); |
352 |
> |
} else { |
353 |
> |
// Two acceptable behaviors: entire removeIf call is one |
354 |
> |
// transaction, or each element processed is one transaction. |
355 |
> |
assertTrue(n == c.size() || n == c.size() + accepts.size()); |
356 |
> |
int k = 0; |
357 |
> |
for (Object x : accepts) if (c.contains(x)) k++; |
358 |
> |
assertTrue(k == accepts.size() || k == 0); |
359 |
> |
} |
360 |
|
} catch (Throwable ex) { |
361 |
|
System.err.println(impl.klazz()); |
362 |
< |
System.err.printf("c=%s%n", c); |
362 |
> |
// c is at risk of corruption if we got here, so be lenient |
363 |
> |
try { System.err.printf("c=%s%n", c); } |
364 |
> |
catch (Throwable t) { t.printStackTrace(); } |
365 |
|
System.err.printf("n=%d%n", n); |
366 |
+ |
System.err.printf("orig=%s%n", orig); |
367 |
|
System.err.printf("accepts=%s%n", accepts); |
368 |
|
System.err.printf("rejects=%s%n", rejects); |
369 |
|
System.err.printf("survivors=%s%n", survivors); |
370 |
< |
System.err.printf("threw=%s%n", threwAt.get()); |
370 |
> |
System.err.printf("threwAt=%s%n", threwAt.get()); |
371 |
|
throw ex; |
372 |
|
} |
373 |
|
} |
374 |
|
|
375 |
|
/** |
376 |
+ |
* All elements removed in the middle of CONCURRENT traversal. |
377 |
+ |
*/ |
378 |
+ |
public void testElementRemovalDuringTraversal() { |
379 |
+ |
Collection c = impl.emptyCollection(); |
380 |
+ |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
381 |
+ |
int n = rnd.nextInt(6); |
382 |
+ |
ArrayList copy = new ArrayList(); |
383 |
+ |
for (int i = 0; i < n; i++) { |
384 |
+ |
Object x = impl.makeElement(i); |
385 |
+ |
copy.add(x); |
386 |
+ |
c.add(x); |
387 |
+ |
} |
388 |
+ |
ArrayList iterated = new ArrayList(); |
389 |
+ |
ArrayList spliterated = new ArrayList(); |
390 |
+ |
Spliterator s = c.spliterator(); |
391 |
+ |
Iterator it = c.iterator(); |
392 |
+ |
for (int i = rnd.nextInt(n + 1); --i >= 0; ) { |
393 |
+ |
assertTrue(s.tryAdvance(spliterated::add)); |
394 |
+ |
if (rnd.nextBoolean()) assertTrue(it.hasNext()); |
395 |
+ |
iterated.add(it.next()); |
396 |
+ |
} |
397 |
+ |
Consumer alwaysThrows = e -> { throw new AssertionError(); }; |
398 |
+ |
if (s.hasCharacteristics(Spliterator.CONCURRENT)) { |
399 |
+ |
c.clear(); // TODO: many more removal methods |
400 |
+ |
if (testImplementationDetails |
401 |
+ |
&& !(c instanceof java.util.concurrent.ArrayBlockingQueue)) { |
402 |
+ |
if (rnd.nextBoolean()) |
403 |
+ |
assertFalse(s.tryAdvance(alwaysThrows)); |
404 |
+ |
else |
405 |
+ |
s.forEachRemaining(alwaysThrows); |
406 |
+ |
} |
407 |
+ |
if (it.hasNext()) iterated.add(it.next()); |
408 |
+ |
if (rnd.nextBoolean()) assertIteratorExhausted(it); |
409 |
+ |
} |
410 |
+ |
assertTrue(copy.containsAll(iterated)); |
411 |
+ |
assertTrue(copy.containsAll(spliterated)); |
412 |
+ |
} |
413 |
+ |
|
414 |
+ |
/** |
415 |
+ |
* Some elements randomly disappear in the middle of traversal. |
416 |
+ |
*/ |
417 |
+ |
public void testRandomElementRemovalDuringTraversal() { |
418 |
+ |
Collection c = impl.emptyCollection(); |
419 |
+ |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
420 |
+ |
int n = rnd.nextInt(6); |
421 |
+ |
ArrayList copy = new ArrayList(); |
422 |
+ |
for (int i = 0; i < n; i++) { |
423 |
+ |
Object x = impl.makeElement(i); |
424 |
+ |
copy.add(x); |
425 |
+ |
c.add(x); |
426 |
+ |
} |
427 |
+ |
ArrayList iterated = new ArrayList(); |
428 |
+ |
ArrayList spliterated = new ArrayList(); |
429 |
+ |
ArrayList removed = new ArrayList(); |
430 |
+ |
Spliterator s = c.spliterator(); |
431 |
+ |
Iterator it = c.iterator(); |
432 |
+ |
if (! (s.hasCharacteristics(Spliterator.CONCURRENT) || |
433 |
+ |
s.hasCharacteristics(Spliterator.IMMUTABLE))) |
434 |
+ |
return; |
435 |
+ |
for (int i = rnd.nextInt(n + 1); --i >= 0; ) { |
436 |
+ |
assertTrue(s.tryAdvance(e -> {})); |
437 |
+ |
if (rnd.nextBoolean()) assertTrue(it.hasNext()); |
438 |
+ |
it.next(); |
439 |
+ |
} |
440 |
+ |
Consumer alwaysThrows = e -> { throw new AssertionError(); }; |
441 |
+ |
// TODO: many more removal methods |
442 |
+ |
if (rnd.nextBoolean()) { |
443 |
+ |
for (Iterator z = c.iterator(); z.hasNext(); ) { |
444 |
+ |
Object e = z.next(); |
445 |
+ |
if (rnd.nextBoolean()) { |
446 |
+ |
try { |
447 |
+ |
z.remove(); |
448 |
+ |
} catch (UnsupportedOperationException ok) { return; } |
449 |
+ |
removed.add(e); |
450 |
+ |
} |
451 |
+ |
} |
452 |
+ |
} else { |
453 |
+ |
Predicate randomlyRemove = e -> { |
454 |
+ |
if (rnd.nextBoolean()) { removed.add(e); return true; } |
455 |
+ |
else return false; |
456 |
+ |
}; |
457 |
+ |
c.removeIf(randomlyRemove); |
458 |
+ |
} |
459 |
+ |
s.forEachRemaining(spliterated::add); |
460 |
+ |
while (it.hasNext()) |
461 |
+ |
iterated.add(it.next()); |
462 |
+ |
assertTrue(copy.containsAll(iterated)); |
463 |
+ |
assertTrue(copy.containsAll(spliterated)); |
464 |
+ |
assertTrue(copy.containsAll(removed)); |
465 |
+ |
if (s.hasCharacteristics(Spliterator.CONCURRENT)) { |
466 |
+ |
ArrayList iteratedAndRemoved = new ArrayList(iterated); |
467 |
+ |
ArrayList spliteratedAndRemoved = new ArrayList(spliterated); |
468 |
+ |
iteratedAndRemoved.retainAll(removed); |
469 |
+ |
spliteratedAndRemoved.retainAll(removed); |
470 |
+ |
assertTrue(iteratedAndRemoved.size() <= 1); |
471 |
+ |
assertTrue(spliteratedAndRemoved.size() <= 1); |
472 |
+ |
if (testImplementationDetails |
473 |
+ |
&& !(c instanceof java.util.concurrent.ArrayBlockingQueue)) |
474 |
+ |
assertTrue(spliteratedAndRemoved.isEmpty()); |
475 |
+ |
} |
476 |
+ |
} |
477 |
+ |
|
478 |
+ |
/** |
479 |
|
* Various ways of traversing a collection yield same elements |
480 |
|
*/ |
481 |
< |
public void testIteratorEquivalence() { |
481 |
> |
public void testTraversalEquivalence() { |
482 |
|
Collection c = impl.emptyCollection(); |
483 |
|
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
484 |
|
int n = rnd.nextInt(6); |
487 |
|
ArrayList iteratedForEachRemaining = new ArrayList(); |
488 |
|
ArrayList tryAdvanced = new ArrayList(); |
489 |
|
ArrayList spliterated = new ArrayList(); |
490 |
+ |
ArrayList splitonced = new ArrayList(); |
491 |
|
ArrayList forEached = new ArrayList(); |
492 |
+ |
ArrayList streamForEached = new ArrayList(); |
493 |
+ |
ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue(); |
494 |
|
ArrayList removeIfed = new ArrayList(); |
495 |
|
for (Object x : c) iterated.add(x); |
496 |
< |
c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e)); |
496 |
> |
c.iterator().forEachRemaining(iteratedForEachRemaining::add); |
497 |
|
for (Spliterator s = c.spliterator(); |
498 |
< |
s.tryAdvance(e -> tryAdvanced.add(e)); ) {} |
499 |
< |
c.spliterator().forEachRemaining(e -> spliterated.add(e)); |
500 |
< |
c.forEach(e -> forEached.add(e)); |
498 |
> |
s.tryAdvance(tryAdvanced::add); ) {} |
499 |
> |
c.spliterator().forEachRemaining(spliterated::add); |
500 |
> |
{ // trySplit returns "strict prefix" |
501 |
> |
Spliterator s1 = c.spliterator(), s2 = s1.trySplit(); |
502 |
> |
if (s2 != null) s2.forEachRemaining(splitonced::add); |
503 |
> |
s1.forEachRemaining(splitonced::add); |
504 |
> |
} |
505 |
> |
c.forEach(forEached::add); |
506 |
> |
c.stream().forEach(streamForEached::add); |
507 |
> |
c.parallelStream().forEach(parallelStreamForEached::add); |
508 |
|
c.removeIf(e -> { removeIfed.add(e); return false; }); |
509 |
|
boolean ordered = |
510 |
|
c.spliterator().hasCharacteristics(Spliterator.ORDERED); |
511 |
|
if (c instanceof List || c instanceof Deque) |
512 |
|
assertTrue(ordered); |
513 |
+ |
HashSet cset = new HashSet(c); |
514 |
+ |
assertEquals(cset, new HashSet(parallelStreamForEached)); |
515 |
|
if (ordered) { |
516 |
|
assertEquals(iterated, iteratedForEachRemaining); |
517 |
|
assertEquals(iterated, tryAdvanced); |
518 |
|
assertEquals(iterated, spliterated); |
519 |
+ |
assertEquals(iterated, splitonced); |
520 |
|
assertEquals(iterated, forEached); |
521 |
+ |
assertEquals(iterated, streamForEached); |
522 |
|
assertEquals(iterated, removeIfed); |
523 |
|
} else { |
270 |
– |
HashSet cset = new HashSet(c); |
524 |
|
assertEquals(cset, new HashSet(iterated)); |
525 |
|
assertEquals(cset, new HashSet(iteratedForEachRemaining)); |
526 |
|
assertEquals(cset, new HashSet(tryAdvanced)); |
527 |
|
assertEquals(cset, new HashSet(spliterated)); |
528 |
+ |
assertEquals(cset, new HashSet(splitonced)); |
529 |
|
assertEquals(cset, new HashSet(forEached)); |
530 |
+ |
assertEquals(cset, new HashSet(streamForEached)); |
531 |
|
assertEquals(cset, new HashSet(removeIfed)); |
532 |
|
} |
533 |
|
if (c instanceof Deque) { |
546 |
|
} |
547 |
|
|
548 |
|
/** |
549 |
+ |
* Iterator.forEachRemaining has same behavior as Iterator's |
550 |
+ |
* default implementation. |
551 |
+ |
*/ |
552 |
+ |
public void testForEachRemainingConsistentWithDefaultImplementation() { |
553 |
+ |
Collection c = impl.emptyCollection(); |
554 |
+ |
if (!testImplementationDetails |
555 |
+ |
|| c.getClass() == java.util.LinkedList.class) |
556 |
+ |
return; |
557 |
+ |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
558 |
+ |
int n = 1 + rnd.nextInt(3); |
559 |
+ |
for (int i = 0; i < n; i++) c.add(impl.makeElement(i)); |
560 |
+ |
ArrayList iterated = new ArrayList(); |
561 |
+ |
ArrayList iteratedForEachRemaining = new ArrayList(); |
562 |
+ |
Iterator it1 = c.iterator(); |
563 |
+ |
Iterator it2 = c.iterator(); |
564 |
+ |
assertTrue(it1.hasNext()); |
565 |
+ |
assertTrue(it2.hasNext()); |
566 |
+ |
c.clear(); |
567 |
+ |
Object r1, r2; |
568 |
+ |
try { |
569 |
+ |
while (it1.hasNext()) iterated.add(it1.next()); |
570 |
+ |
r1 = iterated; |
571 |
+ |
} catch (ConcurrentModificationException ex) { |
572 |
+ |
r1 = ConcurrentModificationException.class; |
573 |
+ |
assertFalse(impl.isConcurrent()); |
574 |
+ |
} |
575 |
+ |
try { |
576 |
+ |
it2.forEachRemaining(iteratedForEachRemaining::add); |
577 |
+ |
r2 = iteratedForEachRemaining; |
578 |
+ |
} catch (ConcurrentModificationException ex) { |
579 |
+ |
r2 = ConcurrentModificationException.class; |
580 |
+ |
assertFalse(impl.isConcurrent()); |
581 |
+ |
} |
582 |
+ |
assertEquals(r1, r2); |
583 |
+ |
} |
584 |
+ |
|
585 |
+ |
/** |
586 |
|
* Calling Iterator#remove() after Iterator#forEachRemaining |
587 |
< |
* should remove last element |
587 |
> |
* should (maybe) remove last element |
588 |
|
*/ |
589 |
|
public void testRemoveAfterForEachRemaining() { |
590 |
|
Collection c = impl.emptyCollection(); |
591 |
|
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
592 |
< |
{ |
592 |
> |
testCollection: { |
593 |
|
int n = 3 + rnd.nextInt(2); |
594 |
|
for (int i = 0; i < n; i++) c.add(impl.makeElement(i)); |
595 |
|
Iterator it = c.iterator(); |
597 |
|
assertEquals(impl.makeElement(0), it.next()); |
598 |
|
assertTrue(it.hasNext()); |
599 |
|
assertEquals(impl.makeElement(1), it.next()); |
600 |
< |
it.forEachRemaining((e) -> {}); |
601 |
< |
it.remove(); |
602 |
< |
assertEquals(n - 1, c.size()); |
603 |
< |
for (int i = 0; i < n - 1; i++) |
604 |
< |
assertTrue(c.contains(impl.makeElement(i))); |
605 |
< |
assertFalse(c.contains(impl.makeElement(n - 1))); |
600 |
> |
it.forEachRemaining(e -> assertTrue(c.contains(e))); |
601 |
> |
if (testImplementationDetails) { |
602 |
> |
if (c instanceof java.util.concurrent.ArrayBlockingQueue) { |
603 |
> |
assertIteratorExhausted(it); |
604 |
> |
} else { |
605 |
> |
try { it.remove(); } |
606 |
> |
catch (UnsupportedOperationException ok) { |
607 |
> |
break testCollection; |
608 |
> |
} |
609 |
> |
assertEquals(n - 1, c.size()); |
610 |
> |
for (int i = 0; i < n - 1; i++) |
611 |
> |
assertTrue(c.contains(impl.makeElement(i))); |
612 |
> |
assertFalse(c.contains(impl.makeElement(n - 1))); |
613 |
> |
} |
614 |
> |
} |
615 |
|
} |
616 |
|
if (c instanceof Deque) { |
617 |
|
Deque d = (Deque) impl.emptyCollection(); |
622 |
|
assertEquals(impl.makeElement(n - 1), it.next()); |
623 |
|
assertTrue(it.hasNext()); |
624 |
|
assertEquals(impl.makeElement(n - 2), it.next()); |
625 |
< |
it.forEachRemaining((e) -> {}); |
626 |
< |
it.remove(); |
627 |
< |
assertEquals(n - 1, d.size()); |
628 |
< |
for (int i = 1; i < n; i++) |
629 |
< |
assertTrue(d.contains(impl.makeElement(i))); |
630 |
< |
assertFalse(d.contains(impl.makeElement(0))); |
625 |
> |
it.forEachRemaining(e -> assertTrue(c.contains(e))); |
626 |
> |
if (testImplementationDetails) { |
627 |
> |
it.remove(); |
628 |
> |
assertEquals(n - 1, d.size()); |
629 |
> |
for (int i = 1; i < n; i++) |
630 |
> |
assertTrue(d.contains(impl.makeElement(i))); |
631 |
> |
assertFalse(d.contains(impl.makeElement(0))); |
632 |
> |
} |
633 |
|
} |
634 |
|
} |
635 |
|
|
642 |
|
final Object x = impl.makeElement(1); |
643 |
|
final Object y = impl.makeElement(2); |
644 |
|
final ArrayList found = new ArrayList(); |
645 |
< |
Consumer<Object> spy = (o) -> { found.add(o); }; |
645 |
> |
Consumer<Object> spy = o -> found.add(o); |
646 |
|
c.stream().forEach(spy); |
647 |
|
assertTrue(found.isEmpty()); |
648 |
|
|
676 |
|
Runnable checkElt = () -> { |
677 |
|
threadsStarted.countDown(); |
678 |
|
while (!done.get()) |
679 |
< |
c.stream().forEach((x) -> { assertSame(x, elt); }); }; |
679 |
> |
c.stream().forEach(x -> assertSame(x, elt)); }; |
680 |
|
Runnable addRemove = () -> { |
681 |
|
threadsStarted.countDown(); |
682 |
|
while (!done.get()) { |
700 |
|
final Object x = impl.makeElement(1); |
701 |
|
final Object y = impl.makeElement(2); |
702 |
|
final ArrayList found = new ArrayList(); |
703 |
< |
Consumer<Object> spy = (o) -> { found.add(o); }; |
703 |
> |
Consumer<Object> spy = o -> found.add(o); |
704 |
|
c.forEach(spy); |
705 |
|
assertTrue(found.isEmpty()); |
706 |
|
|
721 |
|
assertTrue(found.isEmpty()); |
722 |
|
} |
723 |
|
|
724 |
< |
public void testForEachConcurrentStressTest() throws Throwable { |
724 |
> |
/** TODO: promote to a common utility */ |
725 |
> |
static <T> T chooseOne(T ... ts) { |
726 |
> |
return ts[ThreadLocalRandom.current().nextInt(ts.length)]; |
727 |
> |
} |
728 |
> |
|
729 |
> |
/** TODO: more random adders and removers */ |
730 |
> |
static <E> Runnable adderRemover(Collection<E> c, E e) { |
731 |
> |
return chooseOne( |
732 |
> |
() -> { |
733 |
> |
assertTrue(c.add(e)); |
734 |
> |
assertTrue(c.contains(e)); |
735 |
> |
assertTrue(c.remove(e)); |
736 |
> |
assertFalse(c.contains(e)); |
737 |
> |
}, |
738 |
> |
() -> { |
739 |
> |
assertTrue(c.add(e)); |
740 |
> |
assertTrue(c.contains(e)); |
741 |
> |
assertTrue(c.removeIf(x -> x == e)); |
742 |
> |
assertFalse(c.contains(e)); |
743 |
> |
}, |
744 |
> |
() -> { |
745 |
> |
assertTrue(c.add(e)); |
746 |
> |
assertTrue(c.contains(e)); |
747 |
> |
for (Iterator it = c.iterator();; ) |
748 |
> |
if (it.next() == e) { |
749 |
> |
try { it.remove(); } |
750 |
> |
catch (UnsupportedOperationException ok) { |
751 |
> |
c.remove(e); |
752 |
> |
} |
753 |
> |
break; |
754 |
> |
} |
755 |
> |
assertFalse(c.contains(e)); |
756 |
> |
}); |
757 |
> |
} |
758 |
> |
|
759 |
> |
/** |
760 |
> |
* Concurrent Spliterators, once exhausted, stay exhausted. |
761 |
> |
*/ |
762 |
> |
public void testStickySpliteratorExhaustion() throws Throwable { |
763 |
|
if (!impl.isConcurrent()) return; |
764 |
+ |
if (!testImplementationDetails) return; |
765 |
+ |
final ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
766 |
+ |
final Consumer alwaysThrows = e -> { throw new AssertionError(); }; |
767 |
|
final Collection c = impl.emptyCollection(); |
768 |
< |
final long testDurationMillis = timeoutMillis(); |
768 |
> |
final Spliterator s = c.spliterator(); |
769 |
> |
if (rnd.nextBoolean()) { |
770 |
> |
assertFalse(s.tryAdvance(alwaysThrows)); |
771 |
> |
} else { |
772 |
> |
s.forEachRemaining(alwaysThrows); |
773 |
> |
} |
774 |
> |
final Object one = impl.makeElement(1); |
775 |
> |
// Spliterator should not notice added element |
776 |
> |
c.add(one); |
777 |
> |
if (rnd.nextBoolean()) { |
778 |
> |
assertFalse(s.tryAdvance(alwaysThrows)); |
779 |
> |
} else { |
780 |
> |
s.forEachRemaining(alwaysThrows); |
781 |
> |
} |
782 |
> |
} |
783 |
> |
|
784 |
> |
/** |
785 |
> |
* Motley crew of threads concurrently randomly hammer the collection. |
786 |
> |
*/ |
787 |
> |
public void testDetectRaces() throws Throwable { |
788 |
> |
if (!impl.isConcurrent()) return; |
789 |
> |
final ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
790 |
> |
final Collection c = impl.emptyCollection(); |
791 |
> |
final long testDurationMillis |
792 |
> |
= expensiveTests ? LONG_DELAY_MS : timeoutMillis(); |
793 |
|
final AtomicBoolean done = new AtomicBoolean(false); |
794 |
< |
final Object elt = impl.makeElement(1); |
795 |
< |
final Future<?> f1, f2; |
794 |
> |
final Object one = impl.makeElement(1); |
795 |
> |
final Object two = impl.makeElement(2); |
796 |
> |
final Consumer checkSanity = x -> assertTrue(x == one || x == two); |
797 |
> |
final Consumer<Object[]> checkArraySanity = array -> { |
798 |
> |
// assertTrue(array.length <= 2); // duplicates are permitted |
799 |
> |
for (Object x : array) assertTrue(x == one || x == two); |
800 |
> |
}; |
801 |
> |
final Object[] emptyArray = |
802 |
> |
(Object[]) java.lang.reflect.Array.newInstance(one.getClass(), 0); |
803 |
> |
final List<Future<?>> futures; |
804 |
> |
final Phaser threadsStarted = new Phaser(1); // register this thread |
805 |
> |
final Runnable[] frobbers = { |
806 |
> |
() -> c.forEach(checkSanity), |
807 |
> |
() -> c.stream().forEach(checkSanity), |
808 |
> |
() -> c.parallelStream().forEach(checkSanity), |
809 |
> |
() -> c.spliterator().trySplit(), |
810 |
> |
() -> { |
811 |
> |
Spliterator s = c.spliterator(); |
812 |
> |
s.tryAdvance(checkSanity); |
813 |
> |
s.trySplit(); |
814 |
> |
}, |
815 |
> |
() -> { |
816 |
> |
Spliterator s = c.spliterator(); |
817 |
> |
do {} while (s.tryAdvance(checkSanity)); |
818 |
> |
}, |
819 |
> |
() -> { for (Object x : c) checkSanity.accept(x); }, |
820 |
> |
() -> checkArraySanity.accept(c.toArray()), |
821 |
> |
() -> checkArraySanity.accept(c.toArray(emptyArray)), |
822 |
> |
() -> { |
823 |
> |
Object[] a = new Object[5]; |
824 |
> |
Object three = impl.makeElement(3); |
825 |
> |
Arrays.fill(a, 0, a.length, three); |
826 |
> |
Object[] x = c.toArray(a); |
827 |
> |
if (x == a) |
828 |
> |
for (int i = 0; i < a.length && a[i] != null; i++) |
829 |
> |
checkSanity.accept(a[i]); |
830 |
> |
// A careful reading of the spec does not support: |
831 |
> |
// for (i++; i < a.length; i++) assertSame(three, a[i]); |
832 |
> |
else |
833 |
> |
checkArraySanity.accept(x); |
834 |
> |
}, |
835 |
> |
adderRemover(c, one), |
836 |
> |
adderRemover(c, two), |
837 |
> |
}; |
838 |
> |
final List<Runnable> tasks = |
839 |
> |
Arrays.stream(frobbers) |
840 |
> |
.filter(task -> rnd.nextBoolean()) // random subset |
841 |
> |
.map(task -> (Runnable) () -> { |
842 |
> |
threadsStarted.arriveAndAwaitAdvance(); |
843 |
> |
while (!done.get()) |
844 |
> |
task.run(); |
845 |
> |
}) |
846 |
> |
.collect(Collectors.toList()); |
847 |
|
final ExecutorService pool = Executors.newCachedThreadPool(); |
848 |
|
try (PoolCleaner cleaner = cleaner(pool, done)) { |
849 |
< |
final CountDownLatch threadsStarted = new CountDownLatch(2); |
850 |
< |
Runnable checkElt = () -> { |
851 |
< |
threadsStarted.countDown(); |
852 |
< |
while (!done.get()) |
853 |
< |
c.forEach((x) -> { assertSame(x, elt); }); }; |
435 |
< |
Runnable addRemove = () -> { |
436 |
< |
threadsStarted.countDown(); |
437 |
< |
while (!done.get()) { |
438 |
< |
assertTrue(c.add(elt)); |
439 |
< |
assertTrue(c.remove(elt)); |
440 |
< |
}}; |
441 |
< |
f1 = pool.submit(checkElt); |
442 |
< |
f2 = pool.submit(addRemove); |
849 |
> |
threadsStarted.bulkRegister(tasks.size()); |
850 |
> |
futures = tasks.stream() |
851 |
> |
.map(pool::submit) |
852 |
> |
.collect(Collectors.toList()); |
853 |
> |
threadsStarted.arriveAndDeregister(); |
854 |
|
Thread.sleep(testDurationMillis); |
855 |
|
} |
856 |
< |
assertNull(f1.get(0L, MILLISECONDS)); |
857 |
< |
assertNull(f2.get(0L, MILLISECONDS)); |
856 |
> |
for (Future future : futures) |
857 |
> |
assertNull(future.get(0L, MILLISECONDS)); |
858 |
> |
} |
859 |
> |
|
860 |
> |
/** |
861 |
> |
* Spliterators are either IMMUTABLE or truly late-binding or, if |
862 |
> |
* concurrent, use the same "late-binding style" of returning |
863 |
> |
* elements added between creation and first use. |
864 |
> |
*/ |
865 |
> |
public void testLateBindingStyle() { |
866 |
> |
if (!testImplementationDetails) return; |
867 |
> |
if (impl.klazz() == ArrayList.class) return; // for jdk8 |
868 |
> |
// Immutable (snapshot) spliterators are exempt |
869 |
> |
if (impl.emptyCollection().spliterator() |
870 |
> |
.hasCharacteristics(Spliterator.IMMUTABLE)) |
871 |
> |
return; |
872 |
> |
final Object one = impl.makeElement(1); |
873 |
> |
{ |
874 |
> |
final Collection c = impl.emptyCollection(); |
875 |
> |
final Spliterator split = c.spliterator(); |
876 |
> |
c.add(one); |
877 |
> |
assertTrue(split.tryAdvance(e -> { assertSame(e, one); })); |
878 |
> |
assertFalse(split.tryAdvance(e -> { throw new AssertionError(); })); |
879 |
> |
assertTrue(c.contains(one)); |
880 |
> |
} |
881 |
> |
{ |
882 |
> |
final AtomicLong count = new AtomicLong(0); |
883 |
> |
final Collection c = impl.emptyCollection(); |
884 |
> |
final Spliterator split = c.spliterator(); |
885 |
> |
c.add(one); |
886 |
> |
split.forEachRemaining( |
887 |
> |
e -> { assertSame(e, one); count.getAndIncrement(); }); |
888 |
> |
assertEquals(1L, count.get()); |
889 |
> |
assertFalse(split.tryAdvance(e -> { throw new AssertionError(); })); |
890 |
> |
assertTrue(c.contains(one)); |
891 |
> |
} |
892 |
> |
} |
893 |
> |
|
894 |
> |
/** |
895 |
> |
* Spliterator.getComparator throws IllegalStateException iff the |
896 |
> |
* spliterator does not report SORTED. |
897 |
> |
*/ |
898 |
> |
public void testGetComparator_IllegalStateException() { |
899 |
> |
Collection c = impl.emptyCollection(); |
900 |
> |
Spliterator s = c.spliterator(); |
901 |
> |
boolean reportsSorted = s.hasCharacteristics(Spliterator.SORTED); |
902 |
> |
try { |
903 |
> |
s.getComparator(); |
904 |
> |
assertTrue(reportsSorted); |
905 |
> |
} catch (IllegalStateException ex) { |
906 |
> |
assertFalse(reportsSorted); |
907 |
> |
} |
908 |
> |
} |
909 |
> |
|
910 |
> |
public void testCollectionCopies() throws Exception { |
911 |
> |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
912 |
> |
Collection c = impl.emptyCollection(); |
913 |
> |
for (int n = rnd.nextInt(4); n--> 0; ) |
914 |
> |
c.add(impl.makeElement(rnd.nextInt())); |
915 |
> |
assertEquals(c, c); |
916 |
> |
if (c instanceof List) |
917 |
> |
assertCollectionsEquals(c, new ArrayList(c)); |
918 |
> |
else if (c instanceof Set) |
919 |
> |
assertCollectionsEquals(c, new HashSet(c)); |
920 |
> |
else if (c instanceof Deque) |
921 |
> |
assertCollectionsEquivalent(c, new ArrayDeque(c)); |
922 |
> |
|
923 |
> |
Collection clone = cloneableClone(c); |
924 |
> |
if (clone != null) { |
925 |
> |
assertSame(c.getClass(), clone.getClass()); |
926 |
> |
assertCollectionsEquivalent(c, clone); |
927 |
> |
} |
928 |
> |
try { |
929 |
> |
Collection serialClone = serialClonePossiblyFailing(c); |
930 |
> |
assertSame(c.getClass(), serialClone.getClass()); |
931 |
> |
assertCollectionsEquivalent(c, serialClone); |
932 |
> |
} catch (java.io.NotSerializableException acceptable) {} |
933 |
> |
} |
934 |
> |
|
935 |
> |
public void testReplaceAllIsNotStructuralModification() { |
936 |
> |
Collection c = impl.emptyCollection(); |
937 |
> |
if (!(c instanceof List)) |
938 |
> |
return; |
939 |
> |
List list = (List) c; |
940 |
> |
ThreadLocalRandom rnd = ThreadLocalRandom.current(); |
941 |
> |
for (int n = rnd.nextInt(2, 10); n--> 0; ) |
942 |
> |
list.add(impl.makeElement(rnd.nextInt())); |
943 |
> |
ArrayList copy = new ArrayList(list); |
944 |
> |
int size = list.size(), half = size / 2; |
945 |
> |
Iterator it = list.iterator(); |
946 |
> |
for (int i = 0; i < half; i++) |
947 |
> |
assertEquals(it.next(), copy.get(i)); |
948 |
> |
list.replaceAll(n -> n); |
949 |
> |
// ConcurrentModificationException must not be thrown here. |
950 |
> |
for (int i = half; i < size; i++) |
951 |
> |
assertEquals(it.next(), copy.get(i)); |
952 |
|
} |
953 |
|
|
954 |
|
// public void testCollection8DebugFail() { |