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.21 by jsr166, Mon Nov 7 00:37:53 2016 UTC vs.
Revision 1.29 by jsr166, Tue Nov 22 01:08:14 2016 UTC

# Line 25 | Line 25 | import java.util.concurrent.CountDownLat
25   import java.util.concurrent.Executors;
26   import java.util.concurrent.ExecutorService;
27   import java.util.concurrent.Future;
28 + import java.util.concurrent.Phaser;
29   import java.util.concurrent.ThreadLocalRandom;
30   import java.util.concurrent.atomic.AtomicBoolean;
31   import java.util.concurrent.atomic.AtomicLong;
32   import java.util.concurrent.atomic.AtomicReference;
33   import java.util.function.Consumer;
34   import java.util.function.Predicate;
35 + import java.util.stream.Collectors;
36  
37   import junit.framework.Test;
38  
# Line 61 | Line 63 | public class Collection8Test extends JSR
63      }
64  
65      /** Checks properties of empty collections. */
66 <    public void testEmptyMeansEmpty() throws InterruptedException {
66 >    public void testEmptyMeansEmpty() throws Throwable {
67          Collection c = impl.emptyCollection();
68          emptyMeansEmpty(c);
69  
70 <        if (c instanceof java.io.Serializable)
71 <            emptyMeansEmpty(serialClone(c));
70 >        if (c instanceof java.io.Serializable) {
71 >            try {
72 >                emptyMeansEmpty(serialClonePossiblyFailing(c));
73 >            } catch (java.io.NotSerializableException ex) {
74 >                // excusable when we have a serializable wrapper around
75 >                // a non-serializable collection, as can happen with:
76 >                // Vector.subList() => wrapped AbstractList$RandomAccessSubList
77 >                if (testImplementationDetails
78 >                    && (! c.getClass().getName().matches(
79 >                                "java.util.Collections.*")))
80 >                    throw ex;
81 >            }
82 >        }
83  
84          Collection clone = cloneableClone(c);
85          if (clone != null)
# Line 241 | Line 254 | public class Collection8Test extends JSR
254  
255      public void testRemoveIf() {
256          Collection c = impl.emptyCollection();
257 +        boolean ordered =
258 +            c.spliterator().hasCharacteristics(Spliterator.ORDERED);
259          ThreadLocalRandom rnd = ThreadLocalRandom.current();
260          int n = rnd.nextInt(6);
261          for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
# Line 272 | Line 287 | public class Collection8Test extends JSR
287                  assertEquals(modified, accepts.size() > 0);
288                  assertEquals(modified, rejects.size() != n);
289                  assertEquals(accepts.size() + rejects.size(), n);
290 <                assertEquals(rejects, Arrays.asList(c.toArray()));
290 >                if (ordered) {
291 >                    assertEquals(rejects,
292 >                                 Arrays.asList(c.toArray()));
293 >                } else {
294 >                    assertEquals(new HashSet(rejects),
295 >                                 new HashSet(Arrays.asList(c.toArray())));
296 >                }
297              } catch (ArithmeticException ok) {
298                  assertNotNull(threwAt.get());
299                  assertTrue(c.contains(threwAt.get()));
# Line 283 | Line 304 | public class Collection8Test extends JSR
304              switch (rnd.nextInt(4)) {
305              case 0: survivors.addAll(c); break;
306              case 1: survivors.addAll(Arrays.asList(c.toArray())); break;
307 <            case 2: c.forEach(e -> survivors.add(e)); break;
307 >            case 2: c.forEach(survivors::add); break;
308              case 3: for (Object e : c) survivors.add(e); break;
309              }
310              assertTrue(orig.containsAll(accepts));
# Line 293 | Line 314 | public class Collection8Test extends JSR
314              assertTrue(c.containsAll(rejects));
315              assertTrue(c.containsAll(survivors));
316              assertTrue(survivors.containsAll(rejects));
317 <            assertEquals(n - accepts.size(), c.size());
318 <            for (Object x : accepts) assertFalse(c.contains(x));
317 >            if (threwAt.get() == null) {
318 >                assertEquals(n - accepts.size(), c.size());
319 >                for (Object x : accepts) assertFalse(c.contains(x));
320 >            } else {
321 >                // Two acceptable behaviors: entire removeIf call is one
322 >                // transaction, or each element processed is one transaction.
323 >                assertTrue(n == c.size() || n == c.size() + accepts.size());
324 >                int k = 0;
325 >                for (Object x : accepts) if (c.contains(x)) k++;
326 >                assertTrue(k == accepts.size() || k == 0);
327 >            }
328          } catch (Throwable ex) {
329              System.err.println(impl.klazz());
330 <            System.err.printf("c=%s%n", c);
330 >            // c is at risk of corruption if we got here, so be lenient
331 >            try { System.err.printf("c=%s%n", c); }
332 >            catch (Throwable t) { t.printStackTrace(); }
333              System.err.printf("n=%d%n", n);
334              System.err.printf("orig=%s%n", orig);
335              System.err.printf("accepts=%s%n", accepts);
# Line 323 | Line 355 | public class Collection8Test extends JSR
355          ArrayList forEached = new ArrayList();
356          ArrayList removeIfed = new ArrayList();
357          for (Object x : c) iterated.add(x);
358 <        c.iterator().forEachRemaining(e -> iteratedForEachRemaining.add(e));
358 >        c.iterator().forEachRemaining(iteratedForEachRemaining::add);
359          for (Spliterator s = c.spliterator();
360 <             s.tryAdvance(e -> tryAdvanced.add(e)); ) {}
361 <        c.spliterator().forEachRemaining(e -> spliterated.add(e));
362 <        c.forEach(e -> forEached.add(e));
360 >             s.tryAdvance(tryAdvanced::add); ) {}
361 >        c.spliterator().forEachRemaining(spliterated::add);
362 >        c.forEach(forEached::add);
363          c.removeIf(e -> { removeIfed.add(e); return false; });
364          boolean ordered =
365              c.spliterator().hasCharacteristics(Spliterator.ORDERED);
# Line 370 | Line 402 | public class Collection8Test extends JSR
402      public void testRemoveAfterForEachRemaining() {
403          Collection c = impl.emptyCollection();
404          ThreadLocalRandom rnd = ThreadLocalRandom.current();
405 <        {
405 >        testCollection: {
406              int n = 3 + rnd.nextInt(2);
407              for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
408              Iterator it = c.iterator();
# Line 383 | Line 415 | public class Collection8Test extends JSR
415                  if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
416                      assertIteratorExhausted(it);
417                  } else {
418 <                    it.remove();
418 >                    try { it.remove(); }
419 >                    catch (UnsupportedOperationException ok) {
420 >                        break testCollection;
421 >                    }
422                      assertEquals(n - 1, c.size());
423                      for (int i = 0; i < n - 1; i++)
424                          assertTrue(c.contains(impl.makeElement(i)));
# Line 499 | Line 534 | public class Collection8Test extends JSR
534          assertTrue(found.isEmpty());
535      }
536  
537 <    public void testForEachConcurrentStressTest() throws Throwable {
537 >    /**
538 >     * Motley crew of threads concurrently randomly hammer the collection.
539 >     */
540 >    public void testDetectRaces() throws Throwable {
541          if (!impl.isConcurrent()) return;
542 +        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
543          final Collection c = impl.emptyCollection();
544          final long testDurationMillis = timeoutMillis();
545          final AtomicBoolean done = new AtomicBoolean(false);
546 <        final Object elt = impl.makeElement(1);
547 <        final Future<?> f1, f2;
546 >        final Object one = impl.makeElement(1);
547 >        final Object two = impl.makeElement(2);
548 >        final Object[] emptyArray =
549 >            (Object[]) java.lang.reflect.Array.newInstance(one.getClass(), 0);
550 >        final List<Future<?>> futures;
551 >        final Phaser threadsStarted = new Phaser(1); // register this thread
552 >        final Runnable[] frobbers = {
553 >            () -> c.forEach(x -> assertTrue(x == one || x == two)),
554 >            () -> c.stream().forEach(x -> assertTrue(x == one || x == two)),
555 >            () -> c.spliterator().trySplit(),
556 >            () -> {
557 >                Spliterator s = c.spliterator();
558 >                s.tryAdvance(x -> assertTrue(x == one || x == two));
559 >                s.trySplit();
560 >            },
561 >            () -> {
562 >                Spliterator s = c.spliterator();
563 >                do {} while (s.tryAdvance(x -> assertTrue(x == one || x == two)));
564 >            },
565 >            () -> {
566 >                for (Object x : c) assertTrue(x == one || x == two);
567 >            },
568 >            () -> {
569 >                for (Object x : c.toArray()) assertTrue(x == one || x == two);
570 >            },
571 >            () -> {
572 >                for (Object x : c.toArray(emptyArray)) assertTrue(x == one || x == two);
573 >            },
574 >            () -> {
575 >                assertTrue(c.add(one));
576 >                assertTrue(c.contains(one));
577 >                assertTrue(c.remove(one));
578 >                assertFalse(c.contains(one));
579 >            },
580 >            () -> {
581 >                assertTrue(c.add(two));
582 >                assertTrue(c.contains(two));
583 >                assertTrue(c.remove(two));
584 >                assertFalse(c.contains(two));
585 >            },
586 >        };
587 >        final List<Runnable> tasks =
588 >            Arrays.stream(frobbers)
589 >            .filter(task -> rnd.nextBoolean()) // random subset
590 >            .map(task -> (Runnable) () -> {
591 >                     threadsStarted.arriveAndAwaitAdvance();
592 >                     while (!done.get())
593 >                         task.run();
594 >                 })
595 >            .collect(Collectors.toList());
596          final ExecutorService pool = Executors.newCachedThreadPool();
597          try (PoolCleaner cleaner = cleaner(pool, done)) {
598 <            final CountDownLatch threadsStarted = new CountDownLatch(2);
599 <            Runnable checkElt = () -> {
600 <                threadsStarted.countDown();
601 <                while (!done.get())
602 <                    c.forEach(x -> assertSame(x, elt)); };
516 <            Runnable addRemove = () -> {
517 <                threadsStarted.countDown();
518 <                while (!done.get()) {
519 <                    assertTrue(c.add(elt));
520 <                    assertTrue(c.remove(elt));
521 <                }};
522 <            f1 = pool.submit(checkElt);
523 <            f2 = pool.submit(addRemove);
598 >            threadsStarted.bulkRegister(tasks.size());
599 >            futures = tasks.stream()
600 >                .map(pool::submit)
601 >                .collect(Collectors.toList());
602 >            threadsStarted.arriveAndDeregister();
603              Thread.sleep(testDurationMillis);
604          }
605 <        assertNull(f1.get(0L, MILLISECONDS));
606 <        assertNull(f2.get(0L, MILLISECONDS));
605 >        for (Future future : futures)
606 >            assertNull(future.get(0L, MILLISECONDS));
607      }
608  
609   //     public void testCollection8DebugFail() {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines