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.25 by jsr166, Tue Nov 15 00:08:25 2016 UTC vs.
Revision 1.35 by jsr166, Mon Nov 28 17:53:59 2016 UTC

# Line 21 | Line 21 | import java.util.Queue;
21   import java.util.Spliterator;
22   import java.util.concurrent.BlockingDeque;
23   import java.util.concurrent.BlockingQueue;
24 + import java.util.concurrent.ConcurrentLinkedQueue;
25   import java.util.concurrent.CountDownLatch;
26   import java.util.concurrent.Executors;
27   import java.util.concurrent.ExecutorService;
28   import java.util.concurrent.Future;
29 + import java.util.concurrent.Phaser;
30   import java.util.concurrent.ThreadLocalRandom;
31   import java.util.concurrent.atomic.AtomicBoolean;
32   import java.util.concurrent.atomic.AtomicLong;
33   import java.util.concurrent.atomic.AtomicReference;
34   import java.util.function.Consumer;
35   import java.util.function.Predicate;
36 + import java.util.stream.Collectors;
37  
38   import junit.framework.Test;
39  
# Line 302 | Line 305 | public class Collection8Test extends JSR
305              switch (rnd.nextInt(4)) {
306              case 0: survivors.addAll(c); break;
307              case 1: survivors.addAll(Arrays.asList(c.toArray())); break;
308 <            case 2: c.forEach(e -> survivors.add(e)); break;
308 >            case 2: c.forEach(survivors::add); break;
309              case 3: for (Object e : c) survivors.add(e); break;
310              }
311              assertTrue(orig.containsAll(accepts));
# Line 350 | Line 353 | public class Collection8Test extends JSR
353          ArrayList iteratedForEachRemaining = new ArrayList();
354          ArrayList tryAdvanced = new ArrayList();
355          ArrayList spliterated = new ArrayList();
356 +        ArrayList splitonced = new ArrayList();
357          ArrayList forEached = new ArrayList();
358 +        ArrayList streamForEached = new ArrayList();
359 +        ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
360          ArrayList removeIfed = new ArrayList();
361          for (Object x : c) iterated.add(x);
362 <        c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
362 >        c.iterator().forEachRemaining(iteratedForEachRemaining::add);
363          for (Spliterator s = c.spliterator();
364 <             s.tryAdvance(e -> tryAdvanced.add(e)); ) {}
365 <        c.spliterator().forEachRemaining(e -> spliterated.add(e));
366 <        c.forEach(e -> forEached.add(e));
364 >             s.tryAdvance(tryAdvanced::add); ) {}
365 >        c.spliterator().forEachRemaining(spliterated::add);
366 >        {                       // trySplit returns "strict prefix"
367 >            Spliterator s1 = c.spliterator(), s2 = s1.trySplit();
368 >            if (s2 != null) s2.forEachRemaining(splitonced::add);
369 >            s1.forEachRemaining(splitonced::add);
370 >        }
371 >        c.forEach(forEached::add);
372 >        c.stream().forEach(streamForEached::add);
373 >        c.parallelStream().forEach(parallelStreamForEached::add);
374          c.removeIf(e -> { removeIfed.add(e); return false; });
375          boolean ordered =
376              c.spliterator().hasCharacteristics(Spliterator.ORDERED);
377          if (c instanceof List || c instanceof Deque)
378              assertTrue(ordered);
379 +        HashSet cset = new HashSet(c);
380 +        assertEquals(cset, new HashSet(parallelStreamForEached));
381          if (ordered) {
382              assertEquals(iterated, iteratedForEachRemaining);
383              assertEquals(iterated, tryAdvanced);
384              assertEquals(iterated, spliterated);
385 +            assertEquals(iterated, splitonced);
386              assertEquals(iterated, forEached);
387 +            assertEquals(iterated, streamForEached);
388              assertEquals(iterated, removeIfed);
389          } else {
373            HashSet cset = new HashSet(c);
390              assertEquals(cset, new HashSet(iterated));
391              assertEquals(cset, new HashSet(iteratedForEachRemaining));
392              assertEquals(cset, new HashSet(tryAdvanced));
393              assertEquals(cset, new HashSet(spliterated));
394 +            assertEquals(cset, new HashSet(splitonced));
395              assertEquals(cset, new HashSet(forEached));
396 +            assertEquals(cset, new HashSet(streamForEached));
397              assertEquals(cset, new HashSet(removeIfed));
398          }
399          if (c instanceof Deque) {
# Line 532 | Line 550 | public class Collection8Test extends JSR
550          assertTrue(found.isEmpty());
551      }
552  
553 <    public void testForEachConcurrentStressTest() throws Throwable {
553 >    /**
554 >     * Motley crew of threads concurrently randomly hammer the collection.
555 >     */
556 >    public void testDetectRaces() throws Throwable {
557          if (!impl.isConcurrent()) return;
558 +        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
559          final Collection c = impl.emptyCollection();
560 <        final long testDurationMillis = timeoutMillis();
560 >        final long testDurationMillis
561 >            = expensiveTests ? LONG_DELAY_MS : timeoutMillis();
562          final AtomicBoolean done = new AtomicBoolean(false);
563 <        final Object elt = impl.makeElement(1);
564 <        final Future<?> f1, f2;
563 >        final Object one = impl.makeElement(1);
564 >        final Object two = impl.makeElement(2);
565 >        final Consumer checkSanity = x -> assertTrue(x == one || x == two);
566 >        final Object[] emptyArray =
567 >            (Object[]) java.lang.reflect.Array.newInstance(one.getClass(), 0);
568 >        final List<Future<?>> futures;
569 >        final Phaser threadsStarted = new Phaser(1); // register this thread
570 >        final Runnable[] frobbers = {
571 >            () -> c.forEach(checkSanity),
572 >            () -> c.stream().forEach(checkSanity),
573 >            () -> c.parallelStream().forEach(checkSanity),
574 >            () -> c.spliterator().trySplit(),
575 >            () -> {
576 >                Spliterator s = c.spliterator();
577 >                s.tryAdvance(checkSanity);
578 >                s.trySplit();
579 >            },
580 >            () -> {
581 >                Spliterator s = c.spliterator();
582 >                do {} while (s.tryAdvance(checkSanity));
583 >            },
584 >            () -> { for (Object x : c) checkSanity.accept(x); },
585 >            () -> { for (Object x : c.toArray()) checkSanity.accept(x); },
586 >            () -> { for (Object x : c.toArray(emptyArray)) checkSanity.accept(x); },
587 >            () -> {
588 >                assertTrue(c.add(one));
589 >                assertTrue(c.contains(one));
590 >                assertTrue(c.remove(one));
591 >                assertFalse(c.contains(one));
592 >            },
593 >            () -> {
594 >                assertTrue(c.add(two));
595 >                assertTrue(c.contains(two));
596 >                assertTrue(c.remove(two));
597 >                assertFalse(c.contains(two));
598 >            },
599 >        };
600 >        final List<Runnable> tasks =
601 >            Arrays.stream(frobbers)
602 >            .filter(task -> rnd.nextBoolean()) // random subset
603 >            .map(task -> (Runnable) () -> {
604 >                     threadsStarted.arriveAndAwaitAdvance();
605 >                     while (!done.get())
606 >                         task.run();
607 >                 })
608 >            .collect(Collectors.toList());
609          final ExecutorService pool = Executors.newCachedThreadPool();
610          try (PoolCleaner cleaner = cleaner(pool, done)) {
611 <            final CountDownLatch threadsStarted = new CountDownLatch(2);
612 <            Runnable checkElt = () -> {
613 <                threadsStarted.countDown();
614 <                while (!done.get())
615 <                    c.forEach(x -> assertSame(x, elt)); };
549 <            Runnable addRemove = () -> {
550 <                threadsStarted.countDown();
551 <                while (!done.get()) {
552 <                    assertTrue(c.add(elt));
553 <                    assertTrue(c.remove(elt));
554 <                }};
555 <            f1 = pool.submit(checkElt);
556 <            f2 = pool.submit(addRemove);
611 >            threadsStarted.bulkRegister(tasks.size());
612 >            futures = tasks.stream()
613 >                .map(pool::submit)
614 >                .collect(Collectors.toList());
615 >            threadsStarted.arriveAndDeregister();
616              Thread.sleep(testDurationMillis);
617          }
618 <        assertNull(f1.get(0L, MILLISECONDS));
619 <        assertNull(f2.get(0L, MILLISECONDS));
618 >        for (Future future : futures)
619 >            assertNull(future.get(0L, MILLISECONDS));
620 >    }
621 >
622 >    /**
623 >     * Spliterators are either IMMUTABLE or truly late-binding or, if
624 >     * concurrent, use the same "late-binding style" of returning
625 >     * elements added between creation and first use.
626 >     */
627 >    public void testLateBindingStyle() {
628 >        if (!testImplementationDetails) return;
629 >        if (impl.klazz() == ArrayList.class) return; // for jdk8
630 >        // Immutable (snapshot) spliterators are exempt
631 >        if (impl.emptyCollection().spliterator()
632 >            .hasCharacteristics(Spliterator.IMMUTABLE))
633 >            return;
634 >        final Object one = impl.makeElement(1);
635 >        {
636 >            final Collection c = impl.emptyCollection();
637 >            final Spliterator split = c.spliterator();
638 >            c.add(one);
639 >            assertTrue(split.tryAdvance(e -> { assertSame(e, one); }));
640 >            assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
641 >            assertTrue(c.contains(one));
642 >        }
643 >        {
644 >            final AtomicLong count = new AtomicLong(0);
645 >            final Collection c = impl.emptyCollection();
646 >            final Spliterator split = c.spliterator();
647 >            c.add(one);
648 >            split.forEachRemaining(
649 >                e -> { assertSame(e, one); count.getAndIncrement(); });
650 >            assertEquals(1L, count.get());
651 >            assertFalse(split.tryAdvance(e -> { throw new AssertionError(); }));
652 >            assertTrue(c.contains(one));
653 >        }
654      }
655  
656   //     public void testCollection8DebugFail() {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines