ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/Collection8Test.java
(Generate patch)

Comparing jsr166/src/test/tck/Collection8Test.java (file contents):
Revision 1.23 by jsr166, Mon Nov 14 21:33:58 2016 UTC vs.
Revision 1.59 by jsr166, Tue Apr 30 00:50:31 2019 UTC

# Line 8 | Line 8
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  
# Line 55 | Line 61 | public class Collection8Test extends JSR
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() throws InterruptedException {
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)
# Line 77 | Line 95 | public class Collection8Test extends JSR
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);
# Line 125 | Line 160 | public class Collection8Test extends JSR
160          }
161          if (c instanceof BlockingQueue) {
162              BlockingQueue q = (BlockingQueue) c;
163 <            assertNull(q.poll(0L, MILLISECONDS));
163 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
164          }
165          if (c instanceof BlockingDeque) {
166              BlockingDeque q = (BlockingDeque) c;
167 <            assertNull(q.pollFirst(0L, MILLISECONDS));
168 <            assertNull(q.pollLast(0L, MILLISECONDS));
167 >            assertNull(q.pollFirst(randomExpiredTimeout(), randomTimeUnit()));
168 >            assertNull(q.pollLast(randomExpiredTimeout(), randomTimeUnit()));
169          }
170      }
171  
# Line 147 | Line 182 | public class Collection8Test extends JSR
182              () -> c.iterator().forEachRemaining(null),
183              () -> c.spliterator().forEachRemaining(null),
184              () -> c.spliterator().tryAdvance(null),
185 <            () -> c.toArray(null));
185 >            () -> c.toArray((Object[])null));
186  
187          if (!impl.permitsNulls()) {
188              assertThrows(
# Line 175 | Line 210 | public class Collection8Test extends JSR
210              BlockingQueue q = (BlockingQueue) c;
211              assertThrows(
212                  NullPointerException.class,
213 <                () -> {
214 <                    try { q.offer(null, 1L, HOURS); }
180 <                    catch (InterruptedException ex) {
181 <                        throw new AssertionError(ex);
182 <                    }},
183 <                () -> {
184 <                    try { q.put(null); }
185 <                    catch (InterruptedException ex) {
186 <                        throw new AssertionError(ex);
187 <                    }});
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 <                () -> {
221 <                    try { q.offerFirst(null, 1L, HOURS); }
222 <                    catch (InterruptedException ex) {
223 <                        throw new AssertionError(ex);
197 <                    }},
198 <                () -> {
199 <                    try { q.offerLast(null, 1L, HOURS); }
200 <                    catch (InterruptedException ex) {
201 <                        throw new AssertionError(ex);
202 <                    }},
203 <                () -> {
204 <                    try { q.putFirst(null); }
205 <                    catch (InterruptedException ex) {
206 <                        throw new AssertionError(ex);
207 <                    }},
208 <                () -> {
209 <                    try { q.putLast(null); }
210 <                    catch (InterruptedException ex) {
211 <                        throw new AssertionError(ex);
212 <                    }});
220 >                () -> q.offerFirst(null, 1L, HOURS),
221 >                () -> q.offerLast(null, 1L, HOURS),
222 >                () -> q.putFirst(null),
223 >                () -> q.putLast(null));
224          }
225      }
226  
# Line 237 | Line 248 | public class Collection8Test extends JSR
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() {
# Line 291 | Line 312 | public class Collection8Test extends JSR
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(e -> survivors.add(e)); 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));
# Line 328 | Line 349 | public class Collection8Test extends JSR
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 testIteratorEquivalence() {
457 >    public void testTraversalEquivalence() {
458          Collection c = impl.emptyCollection();
459          ThreadLocalRandom rnd = ThreadLocalRandom.current();
460          int n = rnd.nextInt(6);
# Line 339 | Line 463 | public class Collection8Test extends JSR
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(e -> iteratedForEachRemaining.add(e));
472 >        c.iterator().forEachRemaining(iteratedForEachRemaining::add);
473          for (Spliterator s = c.spliterator();
474 <             s.tryAdvance(e -> tryAdvanced.add(e)); ) {}
475 <        c.spliterator().forEachRemaining(e -> spliterated.add(e));
476 <        c.forEach(e -> forEached.add(e));
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 {
362            HashSet cset = new HashSet(c);
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) {
# Line 383 | Line 522 | public class Collection8Test extends JSR
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 <        {
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++) c.add(impl.makeElement(i));
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 <            assertTrue(it.hasNext());
579 <            assertEquals(impl.makeElement(0), it.next());
580 <            assertTrue(it.hasNext());
581 <            assertEquals(impl.makeElement(1), it.next());
582 <            it.forEachRemaining(e -> assertTrue(c.contains(e)));
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 <                    it.remove();
598 >                    try { it.remove(); }
599 >                    catch (UnsupportedOperationException ok) {
600 >                        break testCollection;
601 >                    }
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)));
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();
# Line 518 | Line 717 | public class Collection8Test extends JSR
717          assertTrue(found.isEmpty());
718      }
719  
720 <    public void testForEachConcurrentStressTest() throws Throwable {
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 long testDurationMillis = timeoutMillis();
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 elt = impl.makeElement(1);
791 <        final Future<?> f1, f2;
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 <            final CountDownLatch threadsStarted = new CountDownLatch(2);
846 <            Runnable checkElt = () -> {
847 <                threadsStarted.countDown();
848 <                while (!done.get())
849 <                    c.forEach(x -> assertSame(x, elt)); };
535 <            Runnable addRemove = () -> {
536 <                threadsStarted.countDown();
537 <                while (!done.get()) {
538 <                    assertTrue(c.add(elt));
539 <                    assertTrue(c.remove(elt));
540 <                }};
541 <            f1 = pool.submit(checkElt);
542 <            f2 = pool.submit(addRemove);
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 <        assertNull(f1.get(0L, MILLISECONDS));
853 <        assertNull(f2.get(0L, MILLISECONDS));
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() {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines