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

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.198 by jsr166, Wed Jul 27 17:16:23 2016 UTC vs.
Revision 1.234 by jsr166, Mon Jul 17 22:27:31 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
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   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
# Line 8 | Line 9
9  
10   /*
11   * @test
12 < * @summary JSR-166 tck tests
13 < * @modules java.management
12 > * @summary JSR-166 tck tests, in a number of variations.
13 > *          The first is the conformance testing variant,
14 > *          while others also test implementation details.
15   * @build *
16 < * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
17 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
18 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -Djava.util.secureRandomSeed=true JSR166TestCase
16 > * @modules java.management
17 > * @run junit/othervm/timeout=1000 JSR166TestCase
18 > * @run junit/othervm/timeout=1000
19 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 > *      --add-opens java.base/java.lang=ALL-UNNAMED
21 > *      -Djsr166.testImplementationDetails=true
22 > *      JSR166TestCase
23 > * @run junit/othervm/timeout=1000
24 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 > *      --add-opens java.base/java.lang=ALL-UNNAMED
26 > *      -Djsr166.testImplementationDetails=true
27 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28 > *      JSR166TestCase
29 > * @run junit/othervm/timeout=1000
30 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 > *      --add-opens java.base/java.lang=ALL-UNNAMED
32 > *      -Djsr166.testImplementationDetails=true
33 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
34 > *      -Djava.util.secureRandomSeed=true
35 > *      JSR166TestCase
36 > * @run junit/othervm/timeout=1000/policy=tck.policy
37 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 > *      --add-opens java.base/java.lang=ALL-UNNAMED
39 > *      -Djsr166.testImplementationDetails=true
40 > *      JSR166TestCase
41   */
42  
43   import static java.util.concurrent.TimeUnit.MILLISECONDS;
# Line 30 | Line 54 | import java.lang.management.ThreadMXBean
54   import java.lang.reflect.Constructor;
55   import java.lang.reflect.Method;
56   import java.lang.reflect.Modifier;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 41 | Line 63 | import java.security.ProtectionDomain;
63   import java.security.SecurityPermission;
64   import java.util.ArrayList;
65   import java.util.Arrays;
66 + import java.util.Collection;
67 + import java.util.Collections;
68   import java.util.Date;
69   import java.util.Enumeration;
70   import java.util.Iterator;
# Line 52 | Line 76 | import java.util.concurrent.Callable;
76   import java.util.concurrent.CountDownLatch;
77   import java.util.concurrent.CyclicBarrier;
78   import java.util.concurrent.ExecutionException;
79 + import java.util.concurrent.Executor;
80   import java.util.concurrent.Executors;
81   import java.util.concurrent.ExecutorService;
82   import java.util.concurrent.ForkJoinPool;
83   import java.util.concurrent.Future;
84 + import java.util.concurrent.FutureTask;
85   import java.util.concurrent.RecursiveAction;
86   import java.util.concurrent.RecursiveTask;
87 + import java.util.concurrent.RejectedExecutionException;
88   import java.util.concurrent.RejectedExecutionHandler;
89   import java.util.concurrent.Semaphore;
90 + import java.util.concurrent.ScheduledExecutorService;
91 + import java.util.concurrent.ScheduledFuture;
92   import java.util.concurrent.SynchronousQueue;
93   import java.util.concurrent.ThreadFactory;
94 + import java.util.concurrent.ThreadLocalRandom;
95   import java.util.concurrent.ThreadPoolExecutor;
96 + import java.util.concurrent.TimeUnit;
97   import java.util.concurrent.TimeoutException;
98   import java.util.concurrent.atomic.AtomicBoolean;
99   import java.util.concurrent.atomic.AtomicReference;
69 import java.util.regex.Matcher;
100   import java.util.regex.Pattern;
101  
102   import junit.framework.AssertionFailedError;
# Line 276 | Line 306 | public class JSR166TestCase extends Test
306  
307   //     public static String cpuModel() {
308   //         try {
309 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
309 > //             java.util.regex.Matcher matcher
310 > //               = Pattern.compile("model name\\s*: (.*)")
311   //                 .matcher(new String(
312 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
312 > //                     java.nio.file.Files.readAllBytes(
313 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
314   //             matcher.find();
315   //             return matcher.group(1);
316   //         } catch (Exception ex) { return null; }
# Line 445 | Line 477 | public class JSR166TestCase extends Test
477              AbstractQueuedLongSynchronizerTest.suite(),
478              ArrayBlockingQueueTest.suite(),
479              ArrayDequeTest.suite(),
480 +            ArrayListTest.suite(),
481              AtomicBooleanTest.suite(),
482              AtomicIntegerArrayTest.suite(),
483              AtomicIntegerFieldUpdaterTest.suite(),
# Line 467 | Line 500 | public class JSR166TestCase extends Test
500              CopyOnWriteArrayListTest.suite(),
501              CopyOnWriteArraySetTest.suite(),
502              CountDownLatchTest.suite(),
503 +            CountedCompleterTest.suite(),
504              CyclicBarrierTest.suite(),
505              DelayQueueTest.suite(),
506              EntryTest.suite(),
# Line 495 | Line 529 | public class JSR166TestCase extends Test
529              TreeMapTest.suite(),
530              TreeSetTest.suite(),
531              TreeSubMapTest.suite(),
532 <            TreeSubSetTest.suite());
532 >            TreeSubSetTest.suite(),
533 >            VectorTest.suite());
534  
535          // Java8+ test classes
536          if (atLeastJava8()) {
537              String[] java8TestClassNames = {
538 +                "ArrayDeque8Test",
539                  "Atomic8Test",
540                  "CompletableFutureTest",
541                  "ConcurrentHashMap8Test",
542 <                "CountedCompleterTest",
542 >                "CountedCompleter8Test",
543                  "DoubleAccumulatorTest",
544                  "DoubleAdderTest",
545                  "ForkJoinPool8Test",
546                  "ForkJoinTask8Test",
547 +                "LinkedBlockingDeque8Test",
548 +                "LinkedBlockingQueue8Test",
549                  "LongAccumulatorTest",
550                  "LongAdderTest",
551                  "SplittableRandomTest",
# Line 530 | Line 568 | public class JSR166TestCase extends Test
568                  "AtomicReference9Test",
569                  "AtomicReferenceArray9Test",
570                  "ExecutorCompletionService9Test",
571 +                "ForkJoinPool9Test",
572              };
573              addNamedTestClasses(suite, java9TestClassNames);
574          }
# Line 540 | Line 579 | public class JSR166TestCase extends Test
579      /** Returns list of junit-style test method names in given class. */
580      public static ArrayList<String> testMethodNames(Class<?> testClass) {
581          Method[] methods = testClass.getDeclaredMethods();
582 <        ArrayList<String> names = new ArrayList<String>(methods.length);
582 >        ArrayList<String> names = new ArrayList<>(methods.length);
583          for (Method method : methods) {
584              if (method.getName().startsWith("test")
585                  && Modifier.isPublic(method.getModifiers())
# Line 605 | Line 644 | public class JSR166TestCase extends Test
644      public static long MEDIUM_DELAY_MS;
645      public static long LONG_DELAY_MS;
646  
647 +    private static final long RANDOM_TIMEOUT;
648 +    private static final long RANDOM_EXPIRED_TIMEOUT;
649 +    private static final TimeUnit RANDOM_TIMEUNIT;
650 +    static {
651 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
652 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
653 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
654 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
655 +        TimeUnit[] timeUnits = TimeUnit.values();
656 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
657 +    }
658 +
659 +    /**
660 +     * Returns a timeout for use when any value at all will do.
661 +     */
662 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
663 +
664 +    /**
665 +     * Returns a timeout that means "no waiting", i.e. not positive.
666 +     */
667 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
668 +
669 +    /**
670 +     * Returns a random non-null TimeUnit.
671 +     */
672 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
673 +
674      /**
675       * Returns the shortest timed delay. This can be scaled up for
676       * slow machines using the jsr166.delay.factor system property,
# Line 625 | Line 691 | public class JSR166TestCase extends Test
691          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
692      }
693  
694 +    private static final long TIMEOUT_DELAY_MS
695 +        = (long) (12.0 * Math.cbrt(delayFactor));
696 +
697      /**
698 <     * Returns a timeout in milliseconds to be used in tests that
699 <     * verify that operations block or time out.
698 >     * Returns a timeout in milliseconds to be used in tests that verify
699 >     * that operations block or time out.  We want this to be longer
700 >     * than the OS scheduling quantum, but not too long, so don't scale
701 >     * linearly with delayFactor; we use "crazy" cube root instead.
702       */
703 <    long timeoutMillis() {
704 <        return SHORT_DELAY_MS / 4;
703 >    static long timeoutMillis() {
704 >        return TIMEOUT_DELAY_MS;
705      }
706  
707      /**
# Line 646 | Line 717 | public class JSR166TestCase extends Test
717       * The first exception encountered if any threadAssertXXX method fails.
718       */
719      private final AtomicReference<Throwable> threadFailure
720 <        = new AtomicReference<Throwable>(null);
720 >        = new AtomicReference<>(null);
721  
722      /**
723       * Records an exception so that it can be rethrown later in the test
# Line 1003 | Line 1074 | public class JSR166TestCase extends Test
1074          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1075          System.err.println("------ stacktrace dump start ------");
1076          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1077 <            String name = info.getThreadName();
1077 >            final String name = info.getThreadName();
1078 >            String lockName;
1079              if ("Signal Dispatcher".equals(name))
1080                  continue;
1081              if ("Reference Handler".equals(name)
1082 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1082 >                && (lockName = info.getLockName()) != null
1083 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1084                  continue;
1085              if ("Finalizer".equals(name)
1086 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1086 >                && (lockName = info.getLockName()) != null
1087 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1088                  continue;
1089              if ("checkForWedgedTest".equals(name))
1090                  continue;
# Line 1022 | Line 1096 | public class JSR166TestCase extends Test
1096      }
1097  
1098      /**
1099 +     * Checks that thread eventually enters the expected blocked thread state.
1100 +     */
1101 +    void assertThreadBlocks(Thread thread, Thread.State expected) {
1102 +        // always sleep at least 1 ms, with high probability avoiding
1103 +        // transitory states
1104 +        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1105 +            try { delay(1); }
1106 +            catch (InterruptedException fail) {
1107 +                fail("Unexpected InterruptedException");
1108 +            }
1109 +            Thread.State s = thread.getState();
1110 +            if (s == expected)
1111 +                return;
1112 +            else if (s == Thread.State.TERMINATED)
1113 +                fail("Unexpected thread termination");
1114 +        }
1115 +        fail("timed out waiting for thread to enter thread state " + expected);
1116 +    }
1117 +
1118 +    /**
1119       * Checks that thread does not terminate within the default
1120       * millisecond delay of {@code timeoutMillis()}.
1121 +     * TODO: REMOVEME
1122       */
1123      void assertThreadStaysAlive(Thread thread) {
1124          assertThreadStaysAlive(thread, timeoutMillis());
# Line 1031 | Line 1126 | public class JSR166TestCase extends Test
1126  
1127      /**
1128       * Checks that thread does not terminate within the given millisecond delay.
1129 +     * TODO: REMOVEME
1130       */
1131      void assertThreadStaysAlive(Thread thread, long millis) {
1132          try {
# Line 1045 | Line 1141 | public class JSR166TestCase extends Test
1141      /**
1142       * Checks that the threads do not terminate within the default
1143       * millisecond delay of {@code timeoutMillis()}.
1144 +     * TODO: REMOVEME
1145       */
1146      void assertThreadsStayAlive(Thread... threads) {
1147          assertThreadsStayAlive(timeoutMillis(), threads);
# Line 1052 | Line 1149 | public class JSR166TestCase extends Test
1149  
1150      /**
1151       * Checks that the threads do not terminate within the given millisecond delay.
1152 +     * TODO: REMOVEME
1153       */
1154      void assertThreadsStayAlive(long millis, Thread... threads) {
1155          try {
# Line 1102 | Line 1200 | public class JSR166TestCase extends Test
1200      }
1201  
1202      /**
1203 +     * The maximum number of consecutive spurious wakeups we should
1204 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1205 +     */
1206 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1207 +
1208 +    /**
1209       * The number of elements to place in collections, arrays, etc.
1210       */
1211      public static final int SIZE = 20;
# Line 1205 | Line 1309 | public class JSR166TestCase extends Test
1309          }
1310          public void refresh() {}
1311          public String toString() {
1312 <            List<Permission> ps = new ArrayList<Permission>();
1312 >            List<Permission> ps = new ArrayList<>();
1313              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1314                  ps.add(e.nextElement());
1315              return "AdjustablePolicy with permissions " + ps;
# Line 1235 | Line 1339 | public class JSR166TestCase extends Test
1339       * Sleeps until the given time has elapsed.
1340       * Throws AssertionFailedError if interrupted.
1341       */
1342 <    void sleep(long millis) {
1342 >    static void sleep(long millis) {
1343          try {
1344              delay(millis);
1345          } catch (InterruptedException fail) {
# Line 1251 | Line 1355 | public class JSR166TestCase extends Test
1355       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1356       */
1357      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1358 <        long startTime = System.nanoTime();
1358 >        long startTime = 0L;
1359          for (;;) {
1360              Thread.State s = thread.getState();
1361              if (s == Thread.State.BLOCKED ||
# Line 1260 | Line 1364 | public class JSR166TestCase extends Test
1364                  return;
1365              else if (s == Thread.State.TERMINATED)
1366                  fail("Unexpected thread termination");
1367 +            else if (startTime == 0L)
1368 +                startTime = System.nanoTime();
1369              else if (millisElapsedSince(startTime) > timeoutMillis) {
1370                  threadAssertTrue(thread.isAlive());
1371 <                return;
1371 >                fail("timed out waiting for thread to enter wait state");
1372              }
1373              Thread.yield();
1374          }
1375      }
1376  
1377      /**
1378 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1379 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1378 >     * Spin-waits up to the specified number of milliseconds for the given
1379 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1380 >     * and additionally satisfy the given condition.
1381 >     */
1382 >    void waitForThreadToEnterWaitState(
1383 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1384 >        long startTime = 0L;
1385 >        for (;;) {
1386 >            Thread.State s = thread.getState();
1387 >            if (s == Thread.State.BLOCKED ||
1388 >                s == Thread.State.WAITING ||
1389 >                s == Thread.State.TIMED_WAITING) {
1390 >                try {
1391 >                    if (waitingForGodot.call())
1392 >                        return;
1393 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1394 >            }
1395 >            else if (s == Thread.State.TERMINATED)
1396 >                fail("Unexpected thread termination");
1397 >            else if (startTime == 0L)
1398 >                startTime = System.nanoTime();
1399 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1400 >                threadAssertTrue(thread.isAlive());
1401 >                fail("timed out waiting for thread to enter wait state");
1402 >            }
1403 >            Thread.yield();
1404 >        }
1405 >    }
1406 >
1407 >    /**
1408 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1409 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1410       */
1411      void waitForThreadToEnterWaitState(Thread thread) {
1412          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1413      }
1414  
1415      /**
1416 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1417 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1418 +     * and additionally satisfy the given condition.
1419 +     */
1420 +    void waitForThreadToEnterWaitState(
1421 +        Thread thread, Callable<Boolean> waitingForGodot) {
1422 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1423 +    }
1424 +
1425 +    /**
1426       * Returns the number of milliseconds since time given by
1427       * startNanoTime, which must have been previously returned from a
1428       * call to {@link System#nanoTime()}.
# Line 1528 | Line 1674 | public class JSR166TestCase extends Test
1674          }
1675      }
1676  
1677 +    public void await(CyclicBarrier barrier) {
1678 +        try {
1679 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1680 +        } catch (Throwable fail) {
1681 +            threadUnexpectedException(fail);
1682 +        }
1683 +    }
1684 +
1685   //     /**
1686   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1687   //      */
# Line 1551 | Line 1705 | public class JSR166TestCase extends Test
1705          public String call() { throw new NullPointerException(); }
1706      }
1707  
1554    public static class CallableOne implements Callable<Integer> {
1555        public Integer call() { return one; }
1556    }
1557
1558    public class ShortRunnable extends CheckedRunnable {
1559        protected void realRun() throws Throwable {
1560            delay(SHORT_DELAY_MS);
1561        }
1562    }
1563
1564    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1565        protected void realRun() throws InterruptedException {
1566            delay(SHORT_DELAY_MS);
1567        }
1568    }
1569
1570    public class SmallRunnable extends CheckedRunnable {
1571        protected void realRun() throws Throwable {
1572            delay(SMALL_DELAY_MS);
1573        }
1574    }
1575
1708      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1709          protected void realRun() {
1710              try {
# Line 1581 | Line 1713 | public class JSR166TestCase extends Test
1713          }
1714      }
1715  
1584    public class SmallCallable extends CheckedCallable {
1585        protected Object realCall() throws InterruptedException {
1586            delay(SMALL_DELAY_MS);
1587            return Boolean.TRUE;
1588        }
1589    }
1590
1591    public class MediumRunnable extends CheckedRunnable {
1592        protected void realRun() throws Throwable {
1593            delay(MEDIUM_DELAY_MS);
1594        }
1595    }
1596
1597    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1598        protected void realRun() throws InterruptedException {
1599            delay(MEDIUM_DELAY_MS);
1600        }
1601    }
1602
1716      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1717          return new CheckedRunnable() {
1718              protected void realRun() {
# Line 1609 | Line 1722 | public class JSR166TestCase extends Test
1722              }};
1723      }
1724  
1612    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1613        protected void realRun() {
1614            try {
1615                delay(MEDIUM_DELAY_MS);
1616            } catch (InterruptedException ok) {}
1617        }
1618    }
1619
1620    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1621        protected void realRun() {
1622            try {
1623                delay(LONG_DELAY_MS);
1624            } catch (InterruptedException ok) {}
1625        }
1626    }
1627
1725      /**
1726       * For use as ThreadFactory in constructors
1727       */
# Line 1638 | Line 1735 | public class JSR166TestCase extends Test
1735          boolean isDone();
1736      }
1737  
1641    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1642        return new TrackedRunnable() {
1643                private volatile boolean done = false;
1644                public boolean isDone() { return done; }
1645                public void run() {
1646                    try {
1647                        delay(timeoutMillis);
1648                        done = true;
1649                    } catch (InterruptedException ok) {}
1650                }
1651            };
1652    }
1653
1654    public static class TrackedShortRunnable implements Runnable {
1655        public volatile boolean done = false;
1656        public void run() {
1657            try {
1658                delay(SHORT_DELAY_MS);
1659                done = true;
1660            } catch (InterruptedException ok) {}
1661        }
1662    }
1663
1664    public static class TrackedSmallRunnable implements Runnable {
1665        public volatile boolean done = false;
1666        public void run() {
1667            try {
1668                delay(SMALL_DELAY_MS);
1669                done = true;
1670            } catch (InterruptedException ok) {}
1671        }
1672    }
1673
1674    public static class TrackedMediumRunnable implements Runnable {
1675        public volatile boolean done = false;
1676        public void run() {
1677            try {
1678                delay(MEDIUM_DELAY_MS);
1679                done = true;
1680            } catch (InterruptedException ok) {}
1681        }
1682    }
1683
1684    public static class TrackedLongRunnable implements Runnable {
1685        public volatile boolean done = false;
1686        public void run() {
1687            try {
1688                delay(LONG_DELAY_MS);
1689                done = true;
1690            } catch (InterruptedException ok) {}
1691        }
1692    }
1693
1738      public static class TrackedNoOpRunnable implements Runnable {
1739          public volatile boolean done = false;
1740          public void run() {
# Line 1698 | Line 1742 | public class JSR166TestCase extends Test
1742          }
1743      }
1744  
1701    public static class TrackedCallable implements Callable {
1702        public volatile boolean done = false;
1703        public Object call() {
1704            try {
1705                delay(SMALL_DELAY_MS);
1706                done = true;
1707            } catch (InterruptedException ok) {}
1708            return Boolean.TRUE;
1709        }
1710    }
1711
1745      /**
1746       * Analog of CheckedRunnable for RecursiveAction
1747       */
# Line 1752 | Line 1785 | public class JSR166TestCase extends Test
1785       * A CyclicBarrier that uses timed await and fails with
1786       * AssertionFailedErrors instead of throwing checked exceptions.
1787       */
1788 <    public class CheckedBarrier extends CyclicBarrier {
1788 >    public static class CheckedBarrier extends CyclicBarrier {
1789          public CheckedBarrier(int parties) { super(parties); }
1790  
1791          public int await() {
# Line 1775 | Line 1808 | public class JSR166TestCase extends Test
1808              assertEquals(0, q.size());
1809              assertNull(q.peek());
1810              assertNull(q.poll());
1811 <            assertNull(q.poll(0, MILLISECONDS));
1811 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1812              assertEquals(q.toString(), "[]");
1813              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1814              assertFalse(q.iterator().hasNext());
# Line 1816 | Line 1849 | public class JSR166TestCase extends Test
1849          }
1850      }
1851  
1852 +    void assertImmutable(final Object o) {
1853 +        if (o instanceof Collection) {
1854 +            assertThrows(
1855 +                UnsupportedOperationException.class,
1856 +                new Runnable() { public void run() {
1857 +                        ((Collection) o).add(null);}});
1858 +        }
1859 +    }
1860 +
1861      @SuppressWarnings("unchecked")
1862      <T> T serialClone(T o) {
1863          try {
1864              ObjectInputStream ois = new ObjectInputStream
1865                  (new ByteArrayInputStream(serialBytes(o)));
1866              T clone = (T) ois.readObject();
1867 +            if (o == clone) assertImmutable(o);
1868              assertSame(o.getClass(), clone.getClass());
1869              return clone;
1870          } catch (Throwable fail) {
# Line 1830 | Line 1873 | public class JSR166TestCase extends Test
1873          }
1874      }
1875  
1876 +    /**
1877 +     * A version of serialClone that leaves error handling (for
1878 +     * e.g. NotSerializableException) up to the caller.
1879 +     */
1880 +    @SuppressWarnings("unchecked")
1881 +    <T> T serialClonePossiblyFailing(T o)
1882 +        throws ReflectiveOperationException, java.io.IOException {
1883 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1884 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1885 +        oos.writeObject(o);
1886 +        oos.flush();
1887 +        oos.close();
1888 +        ObjectInputStream ois = new ObjectInputStream
1889 +            (new ByteArrayInputStream(bos.toByteArray()));
1890 +        T clone = (T) ois.readObject();
1891 +        if (o == clone) assertImmutable(o);
1892 +        assertSame(o.getClass(), clone.getClass());
1893 +        return clone;
1894 +    }
1895 +
1896 +    /**
1897 +     * If o implements Cloneable and has a public clone method,
1898 +     * returns a clone of o, else null.
1899 +     */
1900 +    @SuppressWarnings("unchecked")
1901 +    <T> T cloneableClone(T o) {
1902 +        if (!(o instanceof Cloneable)) return null;
1903 +        final T clone;
1904 +        try {
1905 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1906 +        } catch (NoSuchMethodException ok) {
1907 +            return null;
1908 +        } catch (ReflectiveOperationException unexpected) {
1909 +            throw new Error(unexpected);
1910 +        }
1911 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1912 +        assertSame(o.getClass(), clone.getClass());
1913 +        return clone;
1914 +    }
1915 +
1916      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1917                               Runnable... throwingActions) {
1918          for (Runnable throwingAction : throwingActions) {
# Line 1873 | Line 1956 | public class JSR166TestCase extends Test
1956                                 1000L, MILLISECONDS,
1957                                 new SynchronousQueue<Runnable>());
1958  
1959 +    static <T> void shuffle(T[] array) {
1960 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1961 +    }
1962 +
1963 +    // --- Shared assertions for Executor tests ---
1964 +
1965 +    /**
1966 +     * Returns maximum number of tasks that can be submitted to given
1967 +     * pool (with bounded queue) before saturation (when submission
1968 +     * throws RejectedExecutionException).
1969 +     */
1970 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1971 +        BlockingQueue<Runnable> q = pool.getQueue();
1972 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1973 +    }
1974 +
1975 +    @SuppressWarnings("FutureReturnValueIgnored")
1976 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1977 +        try {
1978 +            e.execute((Runnable) null);
1979 +            shouldThrow();
1980 +        } catch (NullPointerException success) {}
1981 +
1982 +        if (! (e instanceof ExecutorService)) return;
1983 +        ExecutorService es = (ExecutorService) e;
1984 +        try {
1985 +            es.submit((Runnable) null);
1986 +            shouldThrow();
1987 +        } catch (NullPointerException success) {}
1988 +        try {
1989 +            es.submit((Runnable) null, Boolean.TRUE);
1990 +            shouldThrow();
1991 +        } catch (NullPointerException success) {}
1992 +        try {
1993 +            es.submit((Callable) null);
1994 +            shouldThrow();
1995 +        } catch (NullPointerException success) {}
1996 +
1997 +        if (! (e instanceof ScheduledExecutorService)) return;
1998 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1999 +        try {
2000 +            ses.schedule((Runnable) null,
2001 +                         randomTimeout(), randomTimeUnit());
2002 +            shouldThrow();
2003 +        } catch (NullPointerException success) {}
2004 +        try {
2005 +            ses.schedule((Callable) null,
2006 +                         randomTimeout(), randomTimeUnit());
2007 +            shouldThrow();
2008 +        } catch (NullPointerException success) {}
2009 +        try {
2010 +            ses.scheduleAtFixedRate((Runnable) null,
2011 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2012 +            shouldThrow();
2013 +        } catch (NullPointerException success) {}
2014 +        try {
2015 +            ses.scheduleWithFixedDelay((Runnable) null,
2016 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2017 +            shouldThrow();
2018 +        } catch (NullPointerException success) {}
2019 +    }
2020 +
2021 +    void setRejectedExecutionHandler(
2022 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2023 +        p.setRejectedExecutionHandler(handler);
2024 +        assertSame(handler, p.getRejectedExecutionHandler());
2025 +    }
2026 +
2027 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2028 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2029 +        final long savedTaskCount = p.getTaskCount();
2030 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2031 +        final int savedQueueSize = p.getQueue().size();
2032 +        final boolean stock = (p.getClass().getClassLoader() == null);
2033 +
2034 +        Runnable r = () -> {};
2035 +        Callable<Boolean> c = () -> Boolean.TRUE;
2036 +
2037 +        class Recorder implements RejectedExecutionHandler {
2038 +            public volatile Runnable r = null;
2039 +            public volatile ThreadPoolExecutor p = null;
2040 +            public void reset() { r = null; p = null; }
2041 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2042 +                assertNull(this.r);
2043 +                assertNull(this.p);
2044 +                this.r = r;
2045 +                this.p = p;
2046 +            }
2047 +        }
2048 +
2049 +        // check custom handler is invoked exactly once per task
2050 +        Recorder recorder = new Recorder();
2051 +        setRejectedExecutionHandler(p, recorder);
2052 +        for (int i = 2; i--> 0; ) {
2053 +            recorder.reset();
2054 +            p.execute(r);
2055 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2056 +                assertSame(r, recorder.r);
2057 +            assertSame(p, recorder.p);
2058 +
2059 +            recorder.reset();
2060 +            assertFalse(p.submit(r).isDone());
2061 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2062 +            assertSame(p, recorder.p);
2063 +
2064 +            recorder.reset();
2065 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2066 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2067 +            assertSame(p, recorder.p);
2068 +
2069 +            recorder.reset();
2070 +            assertFalse(p.submit(c).isDone());
2071 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2072 +            assertSame(p, recorder.p);
2073 +
2074 +            if (p instanceof ScheduledExecutorService) {
2075 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2076 +                ScheduledFuture<?> future;
2077 +
2078 +                recorder.reset();
2079 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2080 +                assertFalse(future.isDone());
2081 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2082 +                assertSame(p, recorder.p);
2083 +
2084 +                recorder.reset();
2085 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2086 +                assertFalse(future.isDone());
2087 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2088 +                assertSame(p, recorder.p);
2089 +
2090 +                recorder.reset();
2091 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2092 +                assertFalse(future.isDone());
2093 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2094 +                assertSame(p, recorder.p);
2095 +
2096 +                recorder.reset();
2097 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2098 +                assertFalse(future.isDone());
2099 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2100 +                assertSame(p, recorder.p);
2101 +            }
2102 +        }
2103 +
2104 +        // Checking our custom handler above should be sufficient, but
2105 +        // we add some integration tests of standard handlers.
2106 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2107 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2108 +
2109 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2110 +        try {
2111 +            p.execute(setThread);
2112 +            shouldThrow();
2113 +        } catch (RejectedExecutionException success) {}
2114 +        assertNull(thread.get());
2115 +
2116 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2117 +        p.execute(setThread);
2118 +        assertNull(thread.get());
2119 +
2120 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2121 +        p.execute(setThread);
2122 +        if (p.isShutdown())
2123 +            assertNull(thread.get());
2124 +        else
2125 +            assertSame(Thread.currentThread(), thread.get());
2126 +
2127 +        setRejectedExecutionHandler(p, savedHandler);
2128 +
2129 +        // check that pool was not perturbed by handlers
2130 +        assertEquals(savedTaskCount, p.getTaskCount());
2131 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2132 +        assertEquals(savedQueueSize, p.getQueue().size());
2133 +    }
2134   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines