ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
Revision: 1.59
Committed: Tue Apr 30 00:50:31 2019 UTC (5 years ago) by jsr166
Branch: MAIN
Changes since 1.58: +5 -1 lines
Log Message:
DISABLE testReplaceAllIsNotStructuralModification

File Contents

# Content
1 /*
2 * Written by Doug Lea and Martin Buchholz with assistance from
3 * members of JCP JSR-166 Expert Group and released to the public
4 * domain, as explained at
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
43 /**
44 * Contains tests applicable to all jdk8+ Collection implementations.
45 * An extension of CollectionTest.
46 */
47 public class Collection8Test extends JSR166TestCase {
48 final CollectionImplementation impl;
49
50 /** Tests are parameterized by a Collection implementation. */
51 Collection8Test(CollectionImplementation impl, String methodName) {
52 super(methodName);
53 this.impl = impl;
54 }
55
56 public static Test testSuite(CollectionImplementation impl) {
57 return parameterizedTestSuite(Collection8Test.class,
58 CollectionImplementation.class,
59 impl);
60 }
61
62 Object bomb() {
63 return new Object() {
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() throws Throwable {
72 Collection c = impl.emptyCollection();
73 emptyMeansEmpty(c);
74
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) 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);
118 assertSame(Object[].class, a.getClass());
119 }
120 {
121 Object[] a = new Object[0];
122 assertSame(a, c.toArray(a));
123 }
124 {
125 Integer[] a = new Integer[0];
126 assertSame(a, c.toArray(a));
127 }
128 {
129 Integer[] a = { 1, 2, 3};
130 assertSame(a, c.toArray(a));
131 assertNull(a[0]);
132 assertSame(2, a[1]);
133 assertSame(3, a[2]);
134 }
135 assertIteratorExhausted(c.iterator());
136 Consumer alwaysThrows = e -> { throw new AssertionError(); };
137 c.forEach(alwaysThrows);
138 c.iterator().forEachRemaining(alwaysThrows);
139 c.spliterator().forEachRemaining(alwaysThrows);
140 assertFalse(c.spliterator().tryAdvance(alwaysThrows));
141 if (c.spliterator().hasCharacteristics(Spliterator.SIZED))
142 assertEquals(0, c.spliterator().estimateSize());
143 assertFalse(c.contains(bomb()));
144 assertFalse(c.remove(bomb()));
145 if (c instanceof Queue) {
146 Queue q = (Queue) c;
147 assertNull(q.peek());
148 assertNull(q.poll());
149 }
150 if (c instanceof Deque) {
151 Deque d = (Deque) c;
152 assertNull(d.peekFirst());
153 assertNull(d.peekLast());
154 assertNull(d.pollFirst());
155 assertNull(d.pollLast());
156 assertIteratorExhausted(d.descendingIterator());
157 d.descendingIterator().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() throws InterruptedException {
173 Collection c = impl.emptyCollection();
174 assertThrows(
175 NullPointerException.class,
176 () -> c.addAll(null),
177 () -> c.containsAll(null),
178 () -> c.retainAll(null),
179 () -> c.removeAll(null),
180 () -> c.removeIf(null),
181 () -> c.forEach(null),
182 () -> c.iterator().forEachRemaining(null),
183 () -> c.spliterator().forEachRemaining(null),
184 () -> c.spliterator().tryAdvance(null),
185 () -> c.toArray((Object[])null));
186
187 if (!impl.permitsNulls()) {
188 assertThrows(
189 NullPointerException.class,
190 () -> c.add(null));
191 }
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() && c instanceof Deque) {
199 Deque d = (Deque) c;
200 assertThrows(
201 NullPointerException.class,
202 () -> d.addFirst(null),
203 () -> d.addLast(null),
204 () -> d.offerFirst(null),
205 () -> d.offerLast(null),
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 () -> q.offer(null, 1L, HOURS),
214 () -> q.put(null));
215 }
216 if (c instanceof BlockingDeque) {
217 BlockingDeque q = (BlockingDeque) c;
218 assertThrows(
219 NullPointerException.class,
220 () -> q.offerFirst(null, 1L, HOURS),
221 () -> q.offerLast(null, 1L, HOURS),
222 () -> q.putFirst(null),
223 () -> q.putLast(null));
224 }
225 }
226
227 public void testNoSuchElementExceptions() {
228 Collection c = impl.emptyCollection();
229 assertThrows(
230 NoSuchElementException.class,
231 () -> c.iterator().next());
232
233 if (c instanceof Queue) {
234 Queue q = (Queue) c;
235 assertThrows(
236 NoSuchElementException.class,
237 () -> q.element(),
238 () -> q.remove());
239 }
240 if (c instanceof Deque) {
241 Deque d = (Deque) c;
242 assertThrows(
243 NoSuchElementException.class,
244 () -> d.getFirst(),
245 () -> d.getLast(),
246 () -> d.removeFirst(),
247 () -> d.removeLast(),
248 () -> d.pop(),
249 () -> d.descendingIterator().next());
250 }
251 if (c instanceof List) {
252 List x = (List) c;
253 assertThrows(
254 NoSuchElementException.class,
255 () -> x.iterator().next(),
256 () -> x.listIterator().next(),
257 () -> x.listIterator(0).next(),
258 () -> x.listIterator().previous(),
259 () -> x.listIterator(0).previous());
260 }
261 }
262
263 public void testRemoveIf() {
264 Collection c = impl.emptyCollection();
265 boolean ordered =
266 c.spliterator().hasCharacteristics(Spliterator.ORDERED);
267 ThreadLocalRandom rnd = ThreadLocalRandom.current();
268 int n = rnd.nextInt(6);
269 for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
270 AtomicReference threwAt = new AtomicReference(null);
271 List orig = rnd.nextBoolean()
272 ? new ArrayList(c)
273 : Arrays.asList(c.toArray());
274
275 // Merely creating an iterator can change ArrayBlockingQueue behavior
276 Iterator it = rnd.nextBoolean() ? c.iterator() : null;
277
278 ArrayList survivors = new ArrayList();
279 ArrayList accepts = new ArrayList();
280 ArrayList rejects = new ArrayList();
281
282 Predicate randomPredicate = e -> {
283 assertNull(threwAt.get());
284 switch (rnd.nextInt(3)) {
285 case 0: accepts.add(e); return true;
286 case 1: rejects.add(e); return false;
287 case 2: threwAt.set(e); throw new ArithmeticException();
288 default: throw new AssertionError();
289 }
290 };
291 try {
292 try {
293 boolean modified = c.removeIf(randomPredicate);
294 assertNull(threwAt.get());
295 assertEquals(modified, accepts.size() > 0);
296 assertEquals(modified, rejects.size() != n);
297 assertEquals(accepts.size() + rejects.size(), n);
298 if (ordered) {
299 assertEquals(rejects,
300 Arrays.asList(c.toArray()));
301 } else {
302 assertEquals(new HashSet(rejects),
303 new HashSet(Arrays.asList(c.toArray())));
304 }
305 } catch (ArithmeticException ok) {
306 assertNotNull(threwAt.get());
307 assertTrue(c.contains(threwAt.get()));
308 }
309 if (it != null && impl.isConcurrent())
310 // check for weakly consistent iterator
311 while (it.hasNext()) assertTrue(orig.contains(it.next()));
312 switch (rnd.nextInt(4)) {
313 case 0: survivors.addAll(c); break;
314 case 1: survivors.addAll(Arrays.asList(c.toArray())); break;
315 case 2: c.forEach(survivors::add); break;
316 case 3: for (Object e : c) survivors.add(e); break;
317 }
318 assertTrue(orig.containsAll(accepts));
319 assertTrue(orig.containsAll(rejects));
320 assertTrue(orig.containsAll(survivors));
321 assertTrue(orig.containsAll(c));
322 assertTrue(c.containsAll(rejects));
323 assertTrue(c.containsAll(survivors));
324 assertTrue(survivors.containsAll(rejects));
325 if (threwAt.get() == null) {
326 assertEquals(n - accepts.size(), c.size());
327 for (Object x : accepts) assertFalse(c.contains(x));
328 } else {
329 // Two acceptable behaviors: entire removeIf call is one
330 // transaction, or each element processed is one transaction.
331 assertTrue(n == c.size() || n == c.size() + accepts.size());
332 int k = 0;
333 for (Object x : accepts) if (c.contains(x)) k++;
334 assertTrue(k == accepts.size() || k == 0);
335 }
336 } catch (Throwable ex) {
337 System.err.println(impl.klazz());
338 // c is at risk of corruption if we got here, so be lenient
339 try { System.err.printf("c=%s%n", c); }
340 catch (Throwable t) { t.printStackTrace(); }
341 System.err.printf("n=%d%n", n);
342 System.err.printf("orig=%s%n", orig);
343 System.err.printf("accepts=%s%n", accepts);
344 System.err.printf("rejects=%s%n", rejects);
345 System.err.printf("survivors=%s%n", survivors);
346 System.err.printf("threwAt=%s%n", threwAt.get());
347 throw ex;
348 }
349 }
350
351 /**
352 * All elements removed in the middle of CONCURRENT traversal.
353 */
354 public void testElementRemovalDuringTraversal() {
355 Collection c = impl.emptyCollection();
356 ThreadLocalRandom rnd = ThreadLocalRandom.current();
357 int n = rnd.nextInt(6);
358 ArrayList copy = new ArrayList();
359 for (int i = 0; i < n; i++) {
360 Object x = impl.makeElement(i);
361 copy.add(x);
362 c.add(x);
363 }
364 ArrayList iterated = new ArrayList();
365 ArrayList spliterated = new ArrayList();
366 Spliterator s = c.spliterator();
367 Iterator it = c.iterator();
368 for (int i = rnd.nextInt(n + 1); --i >= 0; ) {
369 assertTrue(s.tryAdvance(spliterated::add));
370 if (rnd.nextBoolean()) assertTrue(it.hasNext());
371 iterated.add(it.next());
372 }
373 Consumer alwaysThrows = e -> { throw new AssertionError(); };
374 if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
375 c.clear(); // TODO: many more removal methods
376 if (testImplementationDetails
377 && !(c instanceof java.util.concurrent.ArrayBlockingQueue)) {
378 if (rnd.nextBoolean())
379 assertFalse(s.tryAdvance(alwaysThrows));
380 else
381 s.forEachRemaining(alwaysThrows);
382 }
383 if (it.hasNext()) iterated.add(it.next());
384 if (rnd.nextBoolean()) assertIteratorExhausted(it);
385 }
386 assertTrue(copy.containsAll(iterated));
387 assertTrue(copy.containsAll(spliterated));
388 }
389
390 /**
391 * Some elements randomly disappear in the middle of traversal.
392 */
393 public void testRandomElementRemovalDuringTraversal() {
394 Collection c = impl.emptyCollection();
395 ThreadLocalRandom rnd = ThreadLocalRandom.current();
396 int n = rnd.nextInt(6);
397 ArrayList copy = new ArrayList();
398 for (int i = 0; i < n; i++) {
399 Object x = impl.makeElement(i);
400 copy.add(x);
401 c.add(x);
402 }
403 ArrayList iterated = new ArrayList();
404 ArrayList spliterated = new ArrayList();
405 ArrayList removed = new ArrayList();
406 Spliterator s = c.spliterator();
407 Iterator it = c.iterator();
408 if (! (s.hasCharacteristics(Spliterator.CONCURRENT) ||
409 s.hasCharacteristics(Spliterator.IMMUTABLE)))
410 return;
411 for (int i = rnd.nextInt(n + 1); --i >= 0; ) {
412 assertTrue(s.tryAdvance(e -> {}));
413 if (rnd.nextBoolean()) assertTrue(it.hasNext());
414 it.next();
415 }
416 Consumer alwaysThrows = e -> { throw new AssertionError(); };
417 // TODO: many more removal methods
418 if (rnd.nextBoolean()) {
419 for (Iterator z = c.iterator(); z.hasNext(); ) {
420 Object e = z.next();
421 if (rnd.nextBoolean()) {
422 try {
423 z.remove();
424 } catch (UnsupportedOperationException ok) { return; }
425 removed.add(e);
426 }
427 }
428 } else {
429 Predicate randomlyRemove = e -> {
430 if (rnd.nextBoolean()) { removed.add(e); return true; }
431 else return false;
432 };
433 c.removeIf(randomlyRemove);
434 }
435 s.forEachRemaining(spliterated::add);
436 while (it.hasNext())
437 iterated.add(it.next());
438 assertTrue(copy.containsAll(iterated));
439 assertTrue(copy.containsAll(spliterated));
440 assertTrue(copy.containsAll(removed));
441 if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
442 ArrayList iteratedAndRemoved = new ArrayList(iterated);
443 ArrayList spliteratedAndRemoved = new ArrayList(spliterated);
444 iteratedAndRemoved.retainAll(removed);
445 spliteratedAndRemoved.retainAll(removed);
446 assertTrue(iteratedAndRemoved.size() <= 1);
447 assertTrue(spliteratedAndRemoved.size() <= 1);
448 if (testImplementationDetails
449 && !(c instanceof java.util.concurrent.ArrayBlockingQueue))
450 assertTrue(spliteratedAndRemoved.isEmpty());
451 }
452 }
453
454 /**
455 * Various ways of traversing a collection yield same elements
456 */
457 public void testTraversalEquivalence() {
458 Collection c = impl.emptyCollection();
459 ThreadLocalRandom rnd = ThreadLocalRandom.current();
460 int n = rnd.nextInt(6);
461 for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
462 ArrayList iterated = new ArrayList();
463 ArrayList iteratedForEachRemaining = new ArrayList();
464 ArrayList tryAdvanced = new ArrayList();
465 ArrayList spliterated = new ArrayList();
466 ArrayList splitonced = new ArrayList();
467 ArrayList forEached = new ArrayList();
468 ArrayList streamForEached = new ArrayList();
469 ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
470 ArrayList removeIfed = new ArrayList();
471 for (Object x : c) iterated.add(x);
472 c.iterator().forEachRemaining(iteratedForEachRemaining::add);
473 for (Spliterator s = c.spliterator();
474 s.tryAdvance(tryAdvanced::add); ) {}
475 c.spliterator().forEachRemaining(spliterated::add);
476 { // trySplit returns "strict prefix"
477 Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
478 if (s2 != null) s2.forEachRemaining(splitonced::add);
479 s1.forEachRemaining(splitonced::add);
480 }
481 c.forEach(forEached::add);
482 c.stream().forEach(streamForEached::add);
483 c.parallelStream().forEach(parallelStreamForEached::add);
484 c.removeIf(e -> { removeIfed.add(e); return false; });
485 boolean ordered =
486 c.spliterator().hasCharacteristics(Spliterator.ORDERED);
487 if (c instanceof List || c instanceof Deque)
488 assertTrue(ordered);
489 HashSet cset = new HashSet(c);
490 assertEquals(cset, new HashSet(parallelStreamForEached));
491 if (ordered) {
492 assertEquals(iterated, iteratedForEachRemaining);
493 assertEquals(iterated, tryAdvanced);
494 assertEquals(iterated, spliterated);
495 assertEquals(iterated, splitonced);
496 assertEquals(iterated, forEached);
497 assertEquals(iterated, streamForEached);
498 assertEquals(iterated, removeIfed);
499 } else {
500 assertEquals(cset, new HashSet(iterated));
501 assertEquals(cset, new HashSet(iteratedForEachRemaining));
502 assertEquals(cset, new HashSet(tryAdvanced));
503 assertEquals(cset, new HashSet(spliterated));
504 assertEquals(cset, new HashSet(splitonced));
505 assertEquals(cset, new HashSet(forEached));
506 assertEquals(cset, new HashSet(streamForEached));
507 assertEquals(cset, new HashSet(removeIfed));
508 }
509 if (c instanceof Deque) {
510 Deque d = (Deque) c;
511 ArrayList descending = new ArrayList();
512 ArrayList descendingForEachRemaining = new ArrayList();
513 for (Iterator it = d.descendingIterator(); it.hasNext(); )
514 descending.add(it.next());
515 d.descendingIterator().forEachRemaining(
516 e -> descendingForEachRemaining.add(e));
517 Collections.reverse(descending);
518 Collections.reverse(descendingForEachRemaining);
519 assertEquals(iterated, descending);
520 assertEquals(iterated, descendingForEachRemaining);
521 }
522 }
523
524 /**
525 * Iterator.forEachRemaining has same behavior as Iterator's
526 * default implementation.
527 */
528 public void testForEachRemainingConsistentWithDefaultImplementation() {
529 Collection c = impl.emptyCollection();
530 if (!testImplementationDetails
531 || c.getClass() == java.util.LinkedList.class)
532 return;
533 ThreadLocalRandom rnd = ThreadLocalRandom.current();
534 int n = 1 + rnd.nextInt(3);
535 for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
536 ArrayList iterated = new ArrayList();
537 ArrayList iteratedForEachRemaining = new ArrayList();
538 Iterator it1 = c.iterator();
539 Iterator it2 = c.iterator();
540 assertTrue(it1.hasNext());
541 assertTrue(it2.hasNext());
542 c.clear();
543 Object r1, r2;
544 try {
545 while (it1.hasNext()) iterated.add(it1.next());
546 r1 = iterated;
547 } catch (ConcurrentModificationException ex) {
548 r1 = ConcurrentModificationException.class;
549 assertFalse(impl.isConcurrent());
550 }
551 try {
552 it2.forEachRemaining(iteratedForEachRemaining::add);
553 r2 = iteratedForEachRemaining;
554 } catch (ConcurrentModificationException ex) {
555 r2 = ConcurrentModificationException.class;
556 assertFalse(impl.isConcurrent());
557 }
558 assertEquals(r1, r2);
559 }
560
561 /**
562 * Calling Iterator#remove() after Iterator#forEachRemaining
563 * should (maybe) remove last element
564 */
565 public void testRemoveAfterForEachRemaining() {
566 Collection c = impl.emptyCollection();
567 ThreadLocalRandom rnd = ThreadLocalRandom.current();
568 ArrayList copy = new ArrayList();
569 boolean ordered = c.spliterator().hasCharacteristics(Spliterator.ORDERED);
570 testCollection: {
571 int n = 3 + rnd.nextInt(2);
572 for (int i = 0; i < n; i++) {
573 Object x = impl.makeElement(i);
574 c.add(x);
575 copy.add(x);
576 }
577 Iterator it = c.iterator();
578 if (ordered) {
579 if (rnd.nextBoolean()) assertTrue(it.hasNext());
580 assertEquals(impl.makeElement(0), it.next());
581 if (rnd.nextBoolean()) assertTrue(it.hasNext());
582 assertEquals(impl.makeElement(1), it.next());
583 } else {
584 if (rnd.nextBoolean()) assertTrue(it.hasNext());
585 assertTrue(copy.contains(it.next()));
586 if (rnd.nextBoolean()) assertTrue(it.hasNext());
587 assertTrue(copy.contains(it.next()));
588 }
589 if (rnd.nextBoolean()) assertTrue(it.hasNext());
590 it.forEachRemaining(
591 e -> {
592 assertTrue(c.contains(e));
593 assertTrue(copy.contains(e));});
594 if (testImplementationDetails) {
595 if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
596 assertIteratorExhausted(it);
597 } else {
598 try { it.remove(); }
599 catch (UnsupportedOperationException ok) {
600 break testCollection;
601 }
602 assertEquals(n - 1, c.size());
603 if (ordered) {
604 for (int i = 0; i < n - 1; i++)
605 assertTrue(c.contains(impl.makeElement(i)));
606 assertFalse(c.contains(impl.makeElement(n - 1)));
607 }
608 }
609 }
610 }
611 if (c instanceof Deque) {
612 Deque d = (Deque) impl.emptyCollection();
613 assertTrue(ordered);
614 int n = 3 + rnd.nextInt(2);
615 for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
616 Iterator it = d.descendingIterator();
617 assertTrue(it.hasNext());
618 assertEquals(impl.makeElement(n - 1), it.next());
619 assertTrue(it.hasNext());
620 assertEquals(impl.makeElement(n - 2), it.next());
621 it.forEachRemaining(e -> assertTrue(c.contains(e)));
622 if (testImplementationDetails) {
623 it.remove();
624 assertEquals(n - 1, d.size());
625 for (int i = 1; i < n; i++)
626 assertTrue(d.contains(impl.makeElement(i)));
627 assertFalse(d.contains(impl.makeElement(0)));
628 }
629 }
630 }
631
632 /**
633 * stream().forEach returns elements in the collection
634 */
635 public void testStreamForEach() throws Throwable {
636 final Collection c = impl.emptyCollection();
637 final AtomicLong count = new AtomicLong(0L);
638 final Object x = impl.makeElement(1);
639 final Object y = impl.makeElement(2);
640 final ArrayList found = new ArrayList();
641 Consumer<Object> spy = o -> found.add(o);
642 c.stream().forEach(spy);
643 assertTrue(found.isEmpty());
644
645 assertTrue(c.add(x));
646 c.stream().forEach(spy);
647 assertEquals(Collections.singletonList(x), found);
648 found.clear();
649
650 assertTrue(c.add(y));
651 c.stream().forEach(spy);
652 assertEquals(2, found.size());
653 assertTrue(found.contains(x));
654 assertTrue(found.contains(y));
655 found.clear();
656
657 c.clear();
658 c.stream().forEach(spy);
659 assertTrue(found.isEmpty());
660 }
661
662 public void testStreamForEachConcurrentStressTest() throws Throwable {
663 if (!impl.isConcurrent()) return;
664 final Collection c = impl.emptyCollection();
665 final long testDurationMillis = timeoutMillis();
666 final AtomicBoolean done = new AtomicBoolean(false);
667 final Object elt = impl.makeElement(1);
668 final Future<?> f1, f2;
669 final ExecutorService pool = Executors.newCachedThreadPool();
670 try (PoolCleaner cleaner = cleaner(pool, done)) {
671 final CountDownLatch threadsStarted = new CountDownLatch(2);
672 Runnable checkElt = () -> {
673 threadsStarted.countDown();
674 while (!done.get())
675 c.stream().forEach(x -> assertSame(x, elt)); };
676 Runnable addRemove = () -> {
677 threadsStarted.countDown();
678 while (!done.get()) {
679 assertTrue(c.add(elt));
680 assertTrue(c.remove(elt));
681 }};
682 f1 = pool.submit(checkElt);
683 f2 = pool.submit(addRemove);
684 Thread.sleep(testDurationMillis);
685 }
686 assertNull(f1.get(0L, MILLISECONDS));
687 assertNull(f2.get(0L, MILLISECONDS));
688 }
689
690 /**
691 * collection.forEach returns elements in the collection
692 */
693 public void testForEach() throws Throwable {
694 final Collection c = impl.emptyCollection();
695 final AtomicLong count = new AtomicLong(0L);
696 final Object x = impl.makeElement(1);
697 final Object y = impl.makeElement(2);
698 final ArrayList found = new ArrayList();
699 Consumer<Object> spy = o -> found.add(o);
700 c.forEach(spy);
701 assertTrue(found.isEmpty());
702
703 assertTrue(c.add(x));
704 c.forEach(spy);
705 assertEquals(Collections.singletonList(x), found);
706 found.clear();
707
708 assertTrue(c.add(y));
709 c.forEach(spy);
710 assertEquals(2, found.size());
711 assertTrue(found.contains(x));
712 assertTrue(found.contains(y));
713 found.clear();
714
715 c.clear();
716 c.forEach(spy);
717 assertTrue(found.isEmpty());
718 }
719
720 /** TODO: promote to a common utility */
721 static <T> T chooseOne(T ... ts) {
722 return ts[ThreadLocalRandom.current().nextInt(ts.length)];
723 }
724
725 /** TODO: more random adders and removers */
726 static <E> Runnable adderRemover(Collection<E> c, E e) {
727 return chooseOne(
728 () -> {
729 assertTrue(c.add(e));
730 assertTrue(c.contains(e));
731 assertTrue(c.remove(e));
732 assertFalse(c.contains(e));
733 },
734 () -> {
735 assertTrue(c.add(e));
736 assertTrue(c.contains(e));
737 assertTrue(c.removeIf(x -> x == e));
738 assertFalse(c.contains(e));
739 },
740 () -> {
741 assertTrue(c.add(e));
742 assertTrue(c.contains(e));
743 for (Iterator it = c.iterator();; )
744 if (it.next() == e) {
745 try { it.remove(); }
746 catch (UnsupportedOperationException ok) {
747 c.remove(e);
748 }
749 break;
750 }
751 assertFalse(c.contains(e));
752 });
753 }
754
755 /**
756 * Concurrent Spliterators, once exhausted, stay exhausted.
757 */
758 public void testStickySpliteratorExhaustion() throws Throwable {
759 if (!impl.isConcurrent()) return;
760 if (!testImplementationDetails) return;
761 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
762 final Consumer alwaysThrows = e -> { throw new AssertionError(); };
763 final Collection c = impl.emptyCollection();
764 final Spliterator s = c.spliterator();
765 if (rnd.nextBoolean()) {
766 assertFalse(s.tryAdvance(alwaysThrows));
767 } else {
768 s.forEachRemaining(alwaysThrows);
769 }
770 final Object one = impl.makeElement(1);
771 // Spliterator should not notice added element
772 c.add(one);
773 if (rnd.nextBoolean()) {
774 assertFalse(s.tryAdvance(alwaysThrows));
775 } else {
776 s.forEachRemaining(alwaysThrows);
777 }
778 }
779
780 /**
781 * Motley crew of threads concurrently randomly hammer the collection.
782 */
783 public void testDetectRaces() throws Throwable {
784 if (!impl.isConcurrent()) return;
785 final ThreadLocalRandom rnd = ThreadLocalRandom.current();
786 final Collection c = impl.emptyCollection();
787 final long testDurationMillis
788 = expensiveTests ? LONG_DELAY_MS : timeoutMillis();
789 final AtomicBoolean done = new AtomicBoolean(false);
790 final Object one = impl.makeElement(1);
791 final Object two = impl.makeElement(2);
792 final Consumer checkSanity = x -> assertTrue(x == one || x == two);
793 final Consumer<Object[]> checkArraySanity = array -> {
794 // assertTrue(array.length <= 2); // duplicates are permitted
795 for (Object x : array) assertTrue(x == one || x == two);
796 };
797 final Object[] emptyArray =
798 (Object[]) java.lang.reflect.Array.newInstance(one.getClass(), 0);
799 final List<Future<?>> futures;
800 final Phaser threadsStarted = new Phaser(1); // register this thread
801 final Runnable[] frobbers = {
802 () -> c.forEach(checkSanity),
803 () -> c.stream().forEach(checkSanity),
804 () -> c.parallelStream().forEach(checkSanity),
805 () -> c.spliterator().trySplit(),
806 () -> {
807 Spliterator s = c.spliterator();
808 s.tryAdvance(checkSanity);
809 s.trySplit();
810 },
811 () -> {
812 Spliterator s = c.spliterator();
813 do {} while (s.tryAdvance(checkSanity));
814 },
815 () -> { for (Object x : c) checkSanity.accept(x); },
816 () -> checkArraySanity.accept(c.toArray()),
817 () -> checkArraySanity.accept(c.toArray(emptyArray)),
818 () -> {
819 Object[] a = new Object[5];
820 Object three = impl.makeElement(3);
821 Arrays.fill(a, 0, a.length, three);
822 Object[] x = c.toArray(a);
823 if (x == a)
824 for (int i = 0; i < a.length && a[i] != null; i++)
825 checkSanity.accept(a[i]);
826 // A careful reading of the spec does not support:
827 // for (i++; i < a.length; i++) assertSame(three, a[i]);
828 else
829 checkArraySanity.accept(x);
830 },
831 adderRemover(c, one),
832 adderRemover(c, two),
833 };
834 final List<Runnable> tasks =
835 Arrays.stream(frobbers)
836 .filter(task -> rnd.nextBoolean()) // random subset
837 .map(task -> (Runnable) () -> {
838 threadsStarted.arriveAndAwaitAdvance();
839 while (!done.get())
840 task.run();
841 })
842 .collect(Collectors.toList());
843 final ExecutorService pool = Executors.newCachedThreadPool();
844 try (PoolCleaner cleaner = cleaner(pool, done)) {
845 threadsStarted.bulkRegister(tasks.size());
846 futures = tasks.stream()
847 .map(pool::submit)
848 .collect(Collectors.toList());
849 threadsStarted.arriveAndDeregister();
850 Thread.sleep(testDurationMillis);
851 }
852 for (Future future : futures)
853 assertNull(future.get(0L, MILLISECONDS));
854 }
855
856 /**
857 * Spliterators are either IMMUTABLE or truly late-binding or, if
858 * concurrent, use the same "late-binding style" of returning
859 * elements added between creation and first use.
860 */
861 public void testLateBindingStyle() {
862 if (!testImplementationDetails) return;
863 if (impl.klazz() == ArrayList.class) return; // for jdk8
864 // Immutable (snapshot) spliterators are exempt
865 if (impl.emptyCollection().spliterator()
866 .hasCharacteristics(Spliterator.IMMUTABLE))
867 return;
868 final Object one = impl.makeElement(1);
869 {
870 final Collection c = impl.emptyCollection();
871 final Spliterator split = c.spliterator();
872 c.add(one);
873 assertTrue(split.tryAdvance(e -> { assertSame(e, one); }));
874 assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
875 assertTrue(c.contains(one));
876 }
877 {
878 final AtomicLong count = new AtomicLong(0);
879 final Collection c = impl.emptyCollection();
880 final Spliterator split = c.spliterator();
881 c.add(one);
882 split.forEachRemaining(
883 e -> { assertSame(e, one); count.getAndIncrement(); });
884 assertEquals(1L, count.get());
885 assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
886 assertTrue(c.contains(one));
887 }
888 }
889
890 /**
891 * Spliterator.getComparator throws IllegalStateException iff the
892 * spliterator does not report SORTED.
893 */
894 public void testGetComparator_IllegalStateException() {
895 Collection c = impl.emptyCollection();
896 Spliterator s = c.spliterator();
897 boolean reportsSorted = s.hasCharacteristics(Spliterator.SORTED);
898 try {
899 s.getComparator();
900 assertTrue(reportsSorted);
901 } catch (IllegalStateException ex) {
902 assertFalse(reportsSorted);
903 }
904 }
905
906 public void testCollectionCopies() throws Exception {
907 ThreadLocalRandom rnd = ThreadLocalRandom.current();
908 Collection c = impl.emptyCollection();
909 for (int n = rnd.nextInt(4); n--> 0; )
910 c.add(impl.makeElement(rnd.nextInt()));
911 assertEquals(c, c);
912 if (c instanceof List)
913 assertCollectionsEquals(c, new ArrayList(c));
914 else if (c instanceof Set)
915 assertCollectionsEquals(c, new HashSet(c));
916 else if (c instanceof Deque)
917 assertCollectionsEquivalent(c, new ArrayDeque(c));
918
919 Collection clone = cloneableClone(c);
920 if (clone != null) {
921 assertSame(c.getClass(), clone.getClass());
922 assertCollectionsEquivalent(c, clone);
923 }
924 try {
925 Collection serialClone = serialClonePossiblyFailing(c);
926 assertSame(c.getClass(), serialClone.getClass());
927 assertCollectionsEquivalent(c, serialClone);
928 } catch (java.io.NotSerializableException acceptable) {}
929 }
930
931 /**
932 * TODO: move out of limbo
933 * 8203662: remove increment of modCount from ArrayList and Vector replaceAll()
934 */
935 public void DISABLED_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() {
955 // fail(impl.klazz().getSimpleName());
956 // }
957 }