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.38 by jsr166, Wed Dec 7 22:03:41 2016 UTC vs.
Revision 1.60 by jsr166, Mon Dec 16 21:22:33 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;
# Line 58 | 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. */
# Line 91 | 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 139 | 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 161 | 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 189 | 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); }
194 <                    catch (InterruptedException ex) {
195 <                        throw new AssertionError(ex);
196 <                    }},
197 <                () -> {
198 <                    try { q.put(null); }
199 <                    catch (InterruptedException ex) {
200 <                        throw new AssertionError(ex);
201 <                    }});
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);
211 <                    }},
212 <                () -> {
213 <                    try { q.offerLast(null, 1L, HOURS); }
214 <                    catch (InterruptedException ex) {
215 <                        throw new AssertionError(ex);
216 <                    }},
217 <                () -> {
218 <                    try { q.putFirst(null); }
219 <                    catch (InterruptedException ex) {
220 <                        throw new AssertionError(ex);
221 <                    }},
222 <                () -> {
223 <                    try { q.putLast(null); }
224 <                    catch (InterruptedException ex) {
225 <                        throw new AssertionError(ex);
226 <                    }});
220 >                () -> q.offerFirst(null, 1L, HOURS),
221 >                () -> q.offerLast(null, 1L, HOURS),
222 >                () -> q.putFirst(null),
223 >                () -> q.putLast(null));
224          }
225      }
226  
# Line 251 | 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 342 | 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 +        // TODO: many more removal methods
417 +        if (rnd.nextBoolean()) {
418 +            for (Iterator z = c.iterator(); z.hasNext(); ) {
419 +                Object e = z.next();
420 +                if (rnd.nextBoolean()) {
421 +                    try {
422 +                        z.remove();
423 +                    } catch (UnsupportedOperationException ok) { return; }
424 +                    removed.add(e);
425 +                }
426 +            }
427 +        } else {
428 +            Predicate randomlyRemove = e -> {
429 +                if (rnd.nextBoolean()) { removed.add(e); return true; }
430 +                else return false;
431 +            };
432 +            c.removeIf(randomlyRemove);
433 +        }
434 +        s.forEachRemaining(spliterated::add);
435 +        while (it.hasNext())
436 +            iterated.add(it.next());
437 +        assertTrue(copy.containsAll(iterated));
438 +        assertTrue(copy.containsAll(spliterated));
439 +        assertTrue(copy.containsAll(removed));
440 +        if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
441 +            ArrayList iteratedAndRemoved = new ArrayList(iterated);
442 +            ArrayList spliteratedAndRemoved = new ArrayList(spliterated);
443 +            iteratedAndRemoved.retainAll(removed);
444 +            spliteratedAndRemoved.retainAll(removed);
445 +            assertTrue(iteratedAndRemoved.size() <= 1);
446 +            assertTrue(spliteratedAndRemoved.size() <= 1);
447 +            if (testImplementationDetails
448 +                && !(c instanceof java.util.concurrent.ArrayBlockingQueue))
449 +                assertTrue(spliteratedAndRemoved.isEmpty());
450 +        }
451 +    }
452 +
453 +    /**
454       * Various ways of traversing a collection yield same elements
455       */
456 <    public void testIteratorEquivalence() {
456 >    public void testTraversalEquivalence() {
457          Collection c = impl.emptyCollection();
458          ThreadLocalRandom rnd = ThreadLocalRandom.current();
459          int n = rnd.nextInt(6);
# Line 412 | Line 521 | public class Collection8Test extends JSR
521      }
522  
523      /**
524 +     * Iterator.forEachRemaining has same behavior as Iterator's
525 +     * default implementation.
526 +     */
527 +    public void testForEachRemainingConsistentWithDefaultImplementation() {
528 +        Collection c = impl.emptyCollection();
529 +        if (!testImplementationDetails
530 +            || c.getClass() == java.util.LinkedList.class)
531 +            return;
532 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
533 +        int n = 1 + rnd.nextInt(3);
534 +        for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
535 +        ArrayList iterated = new ArrayList();
536 +        ArrayList iteratedForEachRemaining = new ArrayList();
537 +        Iterator it1 = c.iterator();
538 +        Iterator it2 = c.iterator();
539 +        assertTrue(it1.hasNext());
540 +        assertTrue(it2.hasNext());
541 +        c.clear();
542 +        Object r1, r2;
543 +        try {
544 +            while (it1.hasNext()) iterated.add(it1.next());
545 +            r1 = iterated;
546 +        } catch (ConcurrentModificationException ex) {
547 +            r1 = ConcurrentModificationException.class;
548 +            assertFalse(impl.isConcurrent());
549 +        }
550 +        try {
551 +            it2.forEachRemaining(iteratedForEachRemaining::add);
552 +            r2 = iteratedForEachRemaining;
553 +        } catch (ConcurrentModificationException ex) {
554 +            r2 = ConcurrentModificationException.class;
555 +            assertFalse(impl.isConcurrent());
556 +        }
557 +        assertEquals(r1, r2);
558 +    }
559 +
560 +    /**
561       * Calling Iterator#remove() after Iterator#forEachRemaining
562       * should (maybe) remove last element
563       */
564      public void testRemoveAfterForEachRemaining() {
565          Collection c = impl.emptyCollection();
566          ThreadLocalRandom rnd = ThreadLocalRandom.current();
567 +        ArrayList copy = new ArrayList();
568 +        boolean ordered = c.spliterator().hasCharacteristics(Spliterator.ORDERED);
569          testCollection: {
570              int n = 3 + rnd.nextInt(2);
571 <            for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
571 >            for (int i = 0; i < n; i++) {
572 >                Object x = impl.makeElement(i);
573 >                c.add(x);
574 >                copy.add(x);
575 >            }
576              Iterator it = c.iterator();
577 <            assertTrue(it.hasNext());
578 <            assertEquals(impl.makeElement(0), it.next());
579 <            assertTrue(it.hasNext());
580 <            assertEquals(impl.makeElement(1), it.next());
581 <            it.forEachRemaining(e -> assertTrue(c.contains(e)));
577 >            if (ordered) {
578 >                if (rnd.nextBoolean()) assertTrue(it.hasNext());
579 >                assertEquals(impl.makeElement(0), it.next());
580 >                if (rnd.nextBoolean()) assertTrue(it.hasNext());
581 >                assertEquals(impl.makeElement(1), it.next());
582 >            } else {
583 >                if (rnd.nextBoolean()) assertTrue(it.hasNext());
584 >                assertTrue(copy.contains(it.next()));
585 >                if (rnd.nextBoolean()) assertTrue(it.hasNext());
586 >                assertTrue(copy.contains(it.next()));
587 >            }
588 >            if (rnd.nextBoolean()) assertTrue(it.hasNext());
589 >            it.forEachRemaining(
590 >                e -> {
591 >                    assertTrue(c.contains(e));
592 >                    assertTrue(copy.contains(e));});
593              if (testImplementationDetails) {
594                  if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
595                      assertIteratorExhausted(it);
# Line 436 | Line 599 | public class Collection8Test extends JSR
599                          break testCollection;
600                      }
601                      assertEquals(n - 1, c.size());
602 <                    for (int i = 0; i < n - 1; i++)
603 <                        assertTrue(c.contains(impl.makeElement(i)));
604 <                    assertFalse(c.contains(impl.makeElement(n - 1)));
602 >                    if (ordered) {
603 >                        for (int i = 0; i < n - 1; i++)
604 >                            assertTrue(c.contains(impl.makeElement(i)));
605 >                        assertFalse(c.contains(impl.makeElement(n - 1)));
606 >                    }
607                  }
608              }
609          }
610          if (c instanceof Deque) {
611              Deque d = (Deque) impl.emptyCollection();
612 +            assertTrue(ordered);
613              int n = 3 + rnd.nextInt(2);
614              for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
615              Iterator it = d.descendingIterator();
# Line 467 | Line 633 | public class Collection8Test extends JSR
633       */
634      public void testStreamForEach() throws Throwable {
635          final Collection c = impl.emptyCollection();
470        final AtomicLong count = new AtomicLong(0L);
636          final Object x = impl.makeElement(1);
637          final Object y = impl.makeElement(2);
638          final ArrayList found = new ArrayList();
# Line 525 | Line 690 | public class Collection8Test extends JSR
690       */
691      public void testForEach() throws Throwable {
692          final Collection c = impl.emptyCollection();
528        final AtomicLong count = new AtomicLong(0L);
693          final Object x = impl.makeElement(1);
694          final Object y = impl.makeElement(2);
695          final ArrayList found = new ArrayList();
# Line 586 | Line 750 | public class Collection8Test extends JSR
750      }
751  
752      /**
753 +     * Concurrent Spliterators, once exhausted, stay exhausted.
754 +     */
755 +    public void testStickySpliteratorExhaustion() throws Throwable {
756 +        if (!impl.isConcurrent()) return;
757 +        if (!testImplementationDetails) return;
758 +        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
759 +        final Consumer alwaysThrows = e -> { throw new AssertionError(); };
760 +        final Collection c = impl.emptyCollection();
761 +        final Spliterator s = c.spliterator();
762 +        if (rnd.nextBoolean()) {
763 +            assertFalse(s.tryAdvance(alwaysThrows));
764 +        } else {
765 +            s.forEachRemaining(alwaysThrows);
766 +        }
767 +        final Object one = impl.makeElement(1);
768 +        // Spliterator should not notice added element
769 +        c.add(one);
770 +        if (rnd.nextBoolean()) {
771 +            assertFalse(s.tryAdvance(alwaysThrows));
772 +        } else {
773 +            s.forEachRemaining(alwaysThrows);
774 +        }
775 +    }
776 +
777 +    /**
778       * Motley crew of threads concurrently randomly hammer the collection.
779       */
780      public void testDetectRaces() throws Throwable {
# Line 695 | Line 884 | public class Collection8Test extends JSR
884          }
885      }
886  
887 +    /**
888 +     * Spliterator.getComparator throws IllegalStateException iff the
889 +     * spliterator does not report SORTED.
890 +     */
891 +    public void testGetComparator_IllegalStateException() {
892 +        Collection c = impl.emptyCollection();
893 +        Spliterator s = c.spliterator();
894 +        boolean reportsSorted = s.hasCharacteristics(Spliterator.SORTED);
895 +        try {
896 +            s.getComparator();
897 +            assertTrue(reportsSorted);
898 +        } catch (IllegalStateException ex) {
899 +            assertFalse(reportsSorted);
900 +        }
901 +    }
902 +
903 +    public void testCollectionCopies() throws Exception {
904 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
905 +        Collection c = impl.emptyCollection();
906 +        for (int n = rnd.nextInt(4); n--> 0; )
907 +            c.add(impl.makeElement(rnd.nextInt()));
908 +        assertEquals(c, c);
909 +        if (c instanceof List)
910 +            assertCollectionsEquals(c, new ArrayList(c));
911 +        else if (c instanceof Set)
912 +            assertCollectionsEquals(c, new HashSet(c));
913 +        else if (c instanceof Deque)
914 +            assertCollectionsEquivalent(c, new ArrayDeque(c));
915 +
916 +        Collection clone = cloneableClone(c);
917 +        if (clone != null) {
918 +            assertSame(c.getClass(), clone.getClass());
919 +            assertCollectionsEquivalent(c, clone);
920 +        }
921 +        try {
922 +            Collection serialClone = serialClonePossiblyFailing(c);
923 +            assertSame(c.getClass(), serialClone.getClass());
924 +            assertCollectionsEquivalent(c, serialClone);
925 +        } catch (java.io.NotSerializableException acceptable) {}
926 +    }
927 +
928 +    /**
929 +     * TODO: move out of limbo
930 +     * 8203662: remove increment of modCount from ArrayList and Vector replaceAll()
931 +     */
932 +    public void DISABLED_testReplaceAllIsNotStructuralModification() {
933 +        Collection c = impl.emptyCollection();
934 +        if (!(c instanceof List))
935 +            return;
936 +        List list = (List) c;
937 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
938 +        for (int n = rnd.nextInt(2, 10); n--> 0; )
939 +            list.add(impl.makeElement(rnd.nextInt()));
940 +        ArrayList copy = new ArrayList(list);
941 +        int size = list.size(), half = size / 2;
942 +        Iterator it = list.iterator();
943 +        for (int i = 0; i < half; i++)
944 +            assertEquals(it.next(), copy.get(i));
945 +        list.replaceAll(n -> n);
946 +        // ConcurrentModificationException must not be thrown here.
947 +        for (int i = half; i < size; i++)
948 +            assertEquals(it.next(), copy.get(i));
949 +    }
950 +
951   //     public void testCollection8DebugFail() {
952   //         fail(impl.klazz().getSimpleName());
953   //     }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines