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.180 by jsr166, Mon Nov 9 05:43:39 2015 UTC vs.
Revision 1.237 by jsr166, Wed Aug 23 05:33:00 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.
8   */
9  
10 + /*
11 + * @test
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 + * @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;
44   import static java.util.concurrent.TimeUnit.MINUTES;
45   import static java.util.concurrent.TimeUnit.NANOSECONDS;
# Line 20 | 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;
23 import java.nio.file.Files;
24 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 31 | 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 42 | 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;
57 import java.util.regex.Matcher;
100   import java.util.regex.Pattern;
101  
102   import junit.framework.AssertionFailedError;
# Line 175 | Line 217 | public class JSR166TestCase extends Test
217      private static final int suiteRuns =
218          Integer.getInteger("jsr166.suiteRuns", 1);
219  
220 +    /**
221 +     * Returns the value of the system property, or NaN if not defined.
222 +     */
223 +    private static float systemPropertyValue(String name) {
224 +        String floatString = System.getProperty(name);
225 +        if (floatString == null)
226 +            return Float.NaN;
227 +        try {
228 +            return Float.parseFloat(floatString);
229 +        } catch (NumberFormatException ex) {
230 +            throw new IllegalArgumentException(
231 +                String.format("Bad float value in system property %s=%s",
232 +                              name, floatString));
233 +        }
234 +    }
235 +
236 +    /**
237 +     * The scaling factor to apply to standard delays used in tests.
238 +     * May be initialized from any of:
239 +     * - the "jsr166.delay.factor" system property
240 +     * - the "test.timeout.factor" system property (as used by jtreg)
241 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
242 +     * - hard-coded fuzz factor when using a known slowpoke VM
243 +     */
244 +    private static final float delayFactor = delayFactor();
245 +
246 +    private static float delayFactor() {
247 +        float x;
248 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
249 +            return x;
250 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
251 +            return x;
252 +        String prop = System.getProperty("java.vm.version");
253 +        if (prop != null && prop.matches(".*debug.*"))
254 +            return 4.0f; // How much slower is fastdebug than product?!
255 +        return 1.0f;
256 +    }
257 +
258      public JSR166TestCase() { super(); }
259      public JSR166TestCase(String name) { super(name); }
260  
# Line 226 | 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 395 | 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 417 | 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 445 | 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 +                "HashMapTest",
548 +                "LinkedBlockingDeque8Test",
549 +                "LinkedBlockingQueue8Test",
550                  "LongAccumulatorTest",
551                  "LongAdderTest",
552                  "SplittableRandomTest",
553                  "StampedLockTest",
554                  "SubmissionPublisherTest",
555                  "ThreadLocalRandom8Test",
556 +                "TimeUnit8Test",
557              };
558              addNamedTestClasses(suite, java8TestClassNames);
559          }
# Line 471 | Line 561 | public class JSR166TestCase extends Test
561          // Java9+ test classes
562          if (atLeastJava9()) {
563              String[] java9TestClassNames = {
564 <                // Currently empty, but expecting varhandle tests
564 >                "AtomicBoolean9Test",
565 >                "AtomicInteger9Test",
566 >                "AtomicIntegerArray9Test",
567 >                "AtomicLong9Test",
568 >                "AtomicLongArray9Test",
569 >                "AtomicReference9Test",
570 >                "AtomicReferenceArray9Test",
571 >                "ExecutorCompletionService9Test",
572 >                "ForkJoinPool9Test",
573              };
574              addNamedTestClasses(suite, java9TestClassNames);
575          }
# Line 482 | Line 580 | public class JSR166TestCase extends Test
580      /** Returns list of junit-style test method names in given class. */
581      public static ArrayList<String> testMethodNames(Class<?> testClass) {
582          Method[] methods = testClass.getDeclaredMethods();
583 <        ArrayList<String> names = new ArrayList<String>(methods.length);
583 >        ArrayList<String> names = new ArrayList<>(methods.length);
584          for (Method method : methods) {
585              if (method.getName().startsWith("test")
586                  && Modifier.isPublic(method.getModifiers())
# Line 547 | Line 645 | public class JSR166TestCase extends Test
645      public static long MEDIUM_DELAY_MS;
646      public static long LONG_DELAY_MS;
647  
648 +    private static final long RANDOM_TIMEOUT;
649 +    private static final long RANDOM_EXPIRED_TIMEOUT;
650 +    private static final TimeUnit RANDOM_TIMEUNIT;
651 +    static {
652 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
653 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
654 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
655 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
656 +        TimeUnit[] timeUnits = TimeUnit.values();
657 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
658 +    }
659 +
660      /**
661 <     * Returns the shortest timed delay. This could
662 <     * be reimplemented to use for example a Property.
661 >     * Returns a timeout for use when any value at all will do.
662 >     */
663 >    static long randomTimeout() { return RANDOM_TIMEOUT; }
664 >
665 >    /**
666 >     * Returns a timeout that means "no waiting", i.e. not positive.
667 >     */
668 >    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
669 >
670 >    /**
671 >     * Returns a random non-null TimeUnit.
672 >     */
673 >    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
674 >
675 >    /**
676 >     * Returns the shortest timed delay. This can be scaled up for
677 >     * slow machines using the jsr166.delay.factor system property,
678 >     * or via jtreg's -timeoutFactor: flag.
679 >     * http://openjdk.java.net/jtreg/command-help.html
680       */
681      protected long getShortDelay() {
682 <        return 50;
682 >        return (long) (50 * delayFactor);
683      }
684  
685      /**
# Line 565 | Line 692 | public class JSR166TestCase extends Test
692          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
693      }
694  
695 +    private static final long TIMEOUT_DELAY_MS
696 +        = (long) (12.0 * Math.cbrt(delayFactor));
697 +
698      /**
699 <     * Returns a timeout in milliseconds to be used in tests that
700 <     * verify that operations block or time out.
699 >     * Returns a timeout in milliseconds to be used in tests that verify
700 >     * that operations block or time out.  We want this to be longer
701 >     * than the OS scheduling quantum, but not too long, so don't scale
702 >     * linearly with delayFactor; we use "crazy" cube root instead.
703       */
704 <    long timeoutMillis() {
705 <        return SHORT_DELAY_MS / 4;
704 >    static long timeoutMillis() {
705 >        return TIMEOUT_DELAY_MS;
706      }
707  
708      /**
# Line 586 | Line 718 | public class JSR166TestCase extends Test
718       * The first exception encountered if any threadAssertXXX method fails.
719       */
720      private final AtomicReference<Throwable> threadFailure
721 <        = new AtomicReference<Throwable>(null);
721 >        = new AtomicReference<>(null);
722  
723      /**
724       * Records an exception so that it can be rethrown later in the test
# Line 865 | Line 997 | public class JSR166TestCase extends Test
997          }};
998      }
999  
1000 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1001 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
1002 +    }
1003 +
1004 +    Runnable releaser(final AtomicBoolean flag) {
1005 +        return new Runnable() { public void run() { flag.set(true); }};
1006 +    }
1007 +
1008      /**
1009       * Waits out termination of a thread pool or fails doing so.
1010       */
# Line 888 | Line 1028 | public class JSR166TestCase extends Test
1028          }
1029      }
1030  
1031 <    /** Like Runnable, but with the freedom to throw anything */
1031 >    /**
1032 >     * Like Runnable, but with the freedom to throw anything.
1033 >     * junit folks had the same idea:
1034 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1035 >     */
1036      interface Action { public void run() throws Throwable; }
1037  
1038      /**
# Line 919 | Line 1063 | public class JSR166TestCase extends Test
1063       * Uninteresting threads are filtered out.
1064       */
1065      static void dumpTestThreads() {
1066 +        SecurityManager sm = System.getSecurityManager();
1067 +        if (sm != null) {
1068 +            try {
1069 +                System.setSecurityManager(null);
1070 +            } catch (SecurityException giveUp) {
1071 +                return;
1072 +            }
1073 +        }
1074 +
1075          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1076          System.err.println("------ stacktrace dump start ------");
1077          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1078 <            String name = info.getThreadName();
1078 >            final String name = info.getThreadName();
1079 >            String lockName;
1080              if ("Signal Dispatcher".equals(name))
1081                  continue;
1082              if ("Reference Handler".equals(name)
1083 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1083 >                && (lockName = info.getLockName()) != null
1084 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1085                  continue;
1086              if ("Finalizer".equals(name)
1087 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1087 >                && (lockName = info.getLockName()) != null
1088 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1089                  continue;
1090              if ("checkForWedgedTest".equals(name))
1091                  continue;
1092              System.err.print(info);
1093          }
1094          System.err.println("------ stacktrace dump end ------");
939    }
1095  
1096 <    /**
942 <     * Checks that thread does not terminate within the default
943 <     * millisecond delay of {@code timeoutMillis()}.
944 <     */
945 <    void assertThreadStaysAlive(Thread thread) {
946 <        assertThreadStaysAlive(thread, timeoutMillis());
1096 >        if (sm != null) System.setSecurityManager(sm);
1097      }
1098  
1099      /**
1100 <     * Checks that thread does not terminate within the given millisecond delay.
1100 >     * Checks that thread eventually enters the expected blocked thread state.
1101       */
1102 <    void assertThreadStaysAlive(Thread thread, long millis) {
1103 <        try {
1104 <            // No need to optimize the failing case via Thread.join.
1105 <            delay(millis);
1106 <            assertTrue(thread.isAlive());
1107 <        } catch (InterruptedException fail) {
1108 <            threadFail("Unexpected InterruptedException");
1109 <        }
1110 <    }
1111 <
1112 <    /**
1113 <     * Checks that the threads do not terminate within the default
1114 <     * millisecond delay of {@code timeoutMillis()}.
965 <     */
966 <    void assertThreadsStayAlive(Thread... threads) {
967 <        assertThreadsStayAlive(timeoutMillis(), threads);
968 <    }
969 <
970 <    /**
971 <     * Checks that the threads do not terminate within the given millisecond delay.
972 <     */
973 <    void assertThreadsStayAlive(long millis, Thread... threads) {
974 <        try {
975 <            // No need to optimize the failing case via Thread.join.
976 <            delay(millis);
977 <            for (Thread thread : threads)
978 <                assertTrue(thread.isAlive());
979 <        } catch (InterruptedException fail) {
980 <            threadFail("Unexpected InterruptedException");
1102 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1103 >        // always sleep at least 1 ms, with high probability avoiding
1104 >        // transitory states
1105 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1106 >            try { delay(1); }
1107 >            catch (InterruptedException fail) {
1108 >                fail("Unexpected InterruptedException");
1109 >            }
1110 >            Thread.State s = thread.getState();
1111 >            if (s == expected)
1112 >                return;
1113 >            else if (s == Thread.State.TERMINATED)
1114 >                fail("Unexpected thread termination");
1115          }
1116 +        fail("timed out waiting for thread to enter thread state " + expected);
1117      }
1118  
1119      /**
# Line 1019 | Line 1154 | public class JSR166TestCase extends Test
1154      }
1155  
1156      /**
1157 +     * The maximum number of consecutive spurious wakeups we should
1158 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1159 +     */
1160 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1161 +
1162 +    /**
1163       * The number of elements to place in collections, arrays, etc.
1164       */
1165      public static final int SIZE = 20;
# Line 1122 | Line 1263 | public class JSR166TestCase extends Test
1263          }
1264          public void refresh() {}
1265          public String toString() {
1266 <            List<Permission> ps = new ArrayList<Permission>();
1266 >            List<Permission> ps = new ArrayList<>();
1267              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1268                  ps.add(e.nextElement());
1269              return "AdjustablePolicy with permissions " + ps;
# Line 1152 | Line 1293 | public class JSR166TestCase extends Test
1293       * Sleeps until the given time has elapsed.
1294       * Throws AssertionFailedError if interrupted.
1295       */
1296 <    void sleep(long millis) {
1296 >    static void sleep(long millis) {
1297          try {
1298              delay(millis);
1299          } catch (InterruptedException fail) {
# Line 1168 | Line 1309 | public class JSR166TestCase extends Test
1309       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1310       */
1311      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1312 <        long startTime = System.nanoTime();
1312 >        long startTime = 0L;
1313          for (;;) {
1314              Thread.State s = thread.getState();
1315              if (s == Thread.State.BLOCKED ||
# Line 1177 | Line 1318 | public class JSR166TestCase extends Test
1318                  return;
1319              else if (s == Thread.State.TERMINATED)
1320                  fail("Unexpected thread termination");
1321 +            else if (startTime == 0L)
1322 +                startTime = System.nanoTime();
1323              else if (millisElapsedSince(startTime) > timeoutMillis) {
1324                  threadAssertTrue(thread.isAlive());
1325 <                return;
1325 >                fail("timed out waiting for thread to enter wait state");
1326              }
1327              Thread.yield();
1328          }
1329      }
1330  
1331      /**
1332 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1333 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1332 >     * Spin-waits up to the specified number of milliseconds for the given
1333 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1334 >     * and additionally satisfy the given condition.
1335 >     */
1336 >    void waitForThreadToEnterWaitState(
1337 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1338 >        long startTime = 0L;
1339 >        for (;;) {
1340 >            Thread.State s = thread.getState();
1341 >            if (s == Thread.State.BLOCKED ||
1342 >                s == Thread.State.WAITING ||
1343 >                s == Thread.State.TIMED_WAITING) {
1344 >                try {
1345 >                    if (waitingForGodot.call())
1346 >                        return;
1347 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1348 >            }
1349 >            else if (s == Thread.State.TERMINATED)
1350 >                fail("Unexpected thread termination");
1351 >            else if (startTime == 0L)
1352 >                startTime = System.nanoTime();
1353 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1354 >                threadAssertTrue(thread.isAlive());
1355 >                fail("timed out waiting for thread to enter wait state");
1356 >            }
1357 >            Thread.yield();
1358 >        }
1359 >    }
1360 >
1361 >    /**
1362 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1363 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1364       */
1365      void waitForThreadToEnterWaitState(Thread thread) {
1366          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1367      }
1368  
1369      /**
1370 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1371 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1372 +     * and additionally satisfy the given condition.
1373 +     */
1374 +    void waitForThreadToEnterWaitState(
1375 +        Thread thread, Callable<Boolean> waitingForGodot) {
1376 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1377 +    }
1378 +
1379 +    /**
1380       * Returns the number of milliseconds since time given by
1381       * startNanoTime, which must have been previously returned from a
1382       * call to {@link System#nanoTime()}.
# Line 1421 | Line 1604 | public class JSR166TestCase extends Test
1604          return new LatchAwaiter(latch);
1605      }
1606  
1607 <    public void await(CountDownLatch latch) {
1607 >    public void await(CountDownLatch latch, long timeoutMillis) {
1608          try {
1609 <            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1609 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1610                  fail("timed out waiting for CountDownLatch for "
1611 <                     + (LONG_DELAY_MS/1000) + " sec");
1611 >                     + (timeoutMillis/1000) + " sec");
1612          } catch (Throwable fail) {
1613              threadUnexpectedException(fail);
1614          }
1615      }
1616  
1617 +    public void await(CountDownLatch latch) {
1618 +        await(latch, LONG_DELAY_MS);
1619 +    }
1620 +
1621      public void await(Semaphore semaphore) {
1622          try {
1623              if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
# Line 1441 | Line 1628 | public class JSR166TestCase extends Test
1628          }
1629      }
1630  
1631 +    public void await(CyclicBarrier barrier) {
1632 +        try {
1633 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1634 +        } catch (Throwable fail) {
1635 +            threadUnexpectedException(fail);
1636 +        }
1637 +    }
1638 +
1639   //     /**
1640   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1641   //      */
# Line 1464 | Line 1659 | public class JSR166TestCase extends Test
1659          public String call() { throw new NullPointerException(); }
1660      }
1661  
1467    public static class CallableOne implements Callable<Integer> {
1468        public Integer call() { return one; }
1469    }
1470
1471    public class ShortRunnable extends CheckedRunnable {
1472        protected void realRun() throws Throwable {
1473            delay(SHORT_DELAY_MS);
1474        }
1475    }
1476
1477    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1478        protected void realRun() throws InterruptedException {
1479            delay(SHORT_DELAY_MS);
1480        }
1481    }
1482
1483    public class SmallRunnable extends CheckedRunnable {
1484        protected void realRun() throws Throwable {
1485            delay(SMALL_DELAY_MS);
1486        }
1487    }
1488
1662      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1663          protected void realRun() {
1664              try {
# Line 1494 | Line 1667 | public class JSR166TestCase extends Test
1667          }
1668      }
1669  
1497    public class SmallCallable extends CheckedCallable {
1498        protected Object realCall() throws InterruptedException {
1499            delay(SMALL_DELAY_MS);
1500            return Boolean.TRUE;
1501        }
1502    }
1503
1504    public class MediumRunnable extends CheckedRunnable {
1505        protected void realRun() throws Throwable {
1506            delay(MEDIUM_DELAY_MS);
1507        }
1508    }
1509
1510    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1511        protected void realRun() throws InterruptedException {
1512            delay(MEDIUM_DELAY_MS);
1513        }
1514    }
1515
1670      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1671          return new CheckedRunnable() {
1672              protected void realRun() {
# Line 1522 | Line 1676 | public class JSR166TestCase extends Test
1676              }};
1677      }
1678  
1525    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1526        protected void realRun() {
1527            try {
1528                delay(MEDIUM_DELAY_MS);
1529            } catch (InterruptedException ok) {}
1530        }
1531    }
1532
1533    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1534        protected void realRun() {
1535            try {
1536                delay(LONG_DELAY_MS);
1537            } catch (InterruptedException ok) {}
1538        }
1539    }
1540
1679      /**
1680       * For use as ThreadFactory in constructors
1681       */
# Line 1551 | Line 1689 | public class JSR166TestCase extends Test
1689          boolean isDone();
1690      }
1691  
1554    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1555        return new TrackedRunnable() {
1556                private volatile boolean done = false;
1557                public boolean isDone() { return done; }
1558                public void run() {
1559                    try {
1560                        delay(timeoutMillis);
1561                        done = true;
1562                    } catch (InterruptedException ok) {}
1563                }
1564            };
1565    }
1566
1567    public static class TrackedShortRunnable implements Runnable {
1568        public volatile boolean done = false;
1569        public void run() {
1570            try {
1571                delay(SHORT_DELAY_MS);
1572                done = true;
1573            } catch (InterruptedException ok) {}
1574        }
1575    }
1576
1577    public static class TrackedSmallRunnable implements Runnable {
1578        public volatile boolean done = false;
1579        public void run() {
1580            try {
1581                delay(SMALL_DELAY_MS);
1582                done = true;
1583            } catch (InterruptedException ok) {}
1584        }
1585    }
1586
1587    public static class TrackedMediumRunnable implements Runnable {
1588        public volatile boolean done = false;
1589        public void run() {
1590            try {
1591                delay(MEDIUM_DELAY_MS);
1592                done = true;
1593            } catch (InterruptedException ok) {}
1594        }
1595    }
1596
1597    public static class TrackedLongRunnable implements Runnable {
1598        public volatile boolean done = false;
1599        public void run() {
1600            try {
1601                delay(LONG_DELAY_MS);
1602                done = true;
1603            } catch (InterruptedException ok) {}
1604        }
1605    }
1606
1692      public static class TrackedNoOpRunnable implements Runnable {
1693          public volatile boolean done = false;
1694          public void run() {
# Line 1611 | Line 1696 | public class JSR166TestCase extends Test
1696          }
1697      }
1698  
1614    public static class TrackedCallable implements Callable {
1615        public volatile boolean done = false;
1616        public Object call() {
1617            try {
1618                delay(SMALL_DELAY_MS);
1619                done = true;
1620            } catch (InterruptedException ok) {}
1621            return Boolean.TRUE;
1622        }
1623    }
1624
1699      /**
1700       * Analog of CheckedRunnable for RecursiveAction
1701       */
# Line 1665 | Line 1739 | public class JSR166TestCase extends Test
1739       * A CyclicBarrier that uses timed await and fails with
1740       * AssertionFailedErrors instead of throwing checked exceptions.
1741       */
1742 <    public class CheckedBarrier extends CyclicBarrier {
1742 >    public static class CheckedBarrier extends CyclicBarrier {
1743          public CheckedBarrier(int parties) { super(parties); }
1744  
1745          public int await() {
# Line 1688 | Line 1762 | public class JSR166TestCase extends Test
1762              assertEquals(0, q.size());
1763              assertNull(q.peek());
1764              assertNull(q.poll());
1765 <            assertNull(q.poll(0, MILLISECONDS));
1765 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1766              assertEquals(q.toString(), "[]");
1767              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1768              assertFalse(q.iterator().hasNext());
# Line 1729 | Line 1803 | public class JSR166TestCase extends Test
1803          }
1804      }
1805  
1806 +    void assertImmutable(final Object o) {
1807 +        if (o instanceof Collection) {
1808 +            assertThrows(
1809 +                UnsupportedOperationException.class,
1810 +                new Runnable() { public void run() {
1811 +                        ((Collection) o).add(null);}});
1812 +        }
1813 +    }
1814 +
1815      @SuppressWarnings("unchecked")
1816      <T> T serialClone(T o) {
1817          try {
1818              ObjectInputStream ois = new ObjectInputStream
1819                  (new ByteArrayInputStream(serialBytes(o)));
1820              T clone = (T) ois.readObject();
1821 +            if (o == clone) assertImmutable(o);
1822              assertSame(o.getClass(), clone.getClass());
1823              return clone;
1824          } catch (Throwable fail) {
# Line 1743 | Line 1827 | public class JSR166TestCase extends Test
1827          }
1828      }
1829  
1830 +    /**
1831 +     * A version of serialClone that leaves error handling (for
1832 +     * e.g. NotSerializableException) up to the caller.
1833 +     */
1834 +    @SuppressWarnings("unchecked")
1835 +    <T> T serialClonePossiblyFailing(T o)
1836 +        throws ReflectiveOperationException, java.io.IOException {
1837 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1838 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1839 +        oos.writeObject(o);
1840 +        oos.flush();
1841 +        oos.close();
1842 +        ObjectInputStream ois = new ObjectInputStream
1843 +            (new ByteArrayInputStream(bos.toByteArray()));
1844 +        T clone = (T) ois.readObject();
1845 +        if (o == clone) assertImmutable(o);
1846 +        assertSame(o.getClass(), clone.getClass());
1847 +        return clone;
1848 +    }
1849 +
1850 +    /**
1851 +     * If o implements Cloneable and has a public clone method,
1852 +     * returns a clone of o, else null.
1853 +     */
1854 +    @SuppressWarnings("unchecked")
1855 +    <T> T cloneableClone(T o) {
1856 +        if (!(o instanceof Cloneable)) return null;
1857 +        final T clone;
1858 +        try {
1859 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1860 +        } catch (NoSuchMethodException ok) {
1861 +            return null;
1862 +        } catch (ReflectiveOperationException unexpected) {
1863 +            throw new Error(unexpected);
1864 +        }
1865 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1866 +        assertSame(o.getClass(), clone.getClass());
1867 +        return clone;
1868 +    }
1869 +
1870      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1871                               Runnable... throwingActions) {
1872          for (Runnable throwingAction : throwingActions) {
# Line 1771 | Line 1895 | public class JSR166TestCase extends Test
1895          } catch (NoSuchElementException success) {}
1896          assertFalse(it.hasNext());
1897      }
1898 +
1899 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1900 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1901 +    }
1902 +
1903 +    public Runnable runnableThrowing(final RuntimeException ex) {
1904 +        return new Runnable() { public void run() { throw ex; }};
1905 +    }
1906 +
1907 +    /** A reusable thread pool to be shared by tests. */
1908 +    static final ExecutorService cachedThreadPool =
1909 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1910 +                               1000L, MILLISECONDS,
1911 +                               new SynchronousQueue<Runnable>());
1912 +
1913 +    static <T> void shuffle(T[] array) {
1914 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1915 +    }
1916 +
1917 +    /**
1918 +     * Returns the same String as would be returned by {@link
1919 +     * Object#toString}, whether or not the given object's class
1920 +     * overrides toString().
1921 +     *
1922 +     * @see System#identityHashCode
1923 +     */
1924 +    static String identityString(Object x) {
1925 +        return x.getClass().getName()
1926 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1927 +    }
1928 +
1929 +    // --- Shared assertions for Executor tests ---
1930 +
1931 +    /**
1932 +     * Returns maximum number of tasks that can be submitted to given
1933 +     * pool (with bounded queue) before saturation (when submission
1934 +     * throws RejectedExecutionException).
1935 +     */
1936 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1937 +        BlockingQueue<Runnable> q = pool.getQueue();
1938 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1939 +    }
1940 +
1941 +    @SuppressWarnings("FutureReturnValueIgnored")
1942 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1943 +        try {
1944 +            e.execute((Runnable) null);
1945 +            shouldThrow();
1946 +        } catch (NullPointerException success) {}
1947 +
1948 +        if (! (e instanceof ExecutorService)) return;
1949 +        ExecutorService es = (ExecutorService) e;
1950 +        try {
1951 +            es.submit((Runnable) null);
1952 +            shouldThrow();
1953 +        } catch (NullPointerException success) {}
1954 +        try {
1955 +            es.submit((Runnable) null, Boolean.TRUE);
1956 +            shouldThrow();
1957 +        } catch (NullPointerException success) {}
1958 +        try {
1959 +            es.submit((Callable) null);
1960 +            shouldThrow();
1961 +        } catch (NullPointerException success) {}
1962 +
1963 +        if (! (e instanceof ScheduledExecutorService)) return;
1964 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1965 +        try {
1966 +            ses.schedule((Runnable) null,
1967 +                         randomTimeout(), randomTimeUnit());
1968 +            shouldThrow();
1969 +        } catch (NullPointerException success) {}
1970 +        try {
1971 +            ses.schedule((Callable) null,
1972 +                         randomTimeout(), randomTimeUnit());
1973 +            shouldThrow();
1974 +        } catch (NullPointerException success) {}
1975 +        try {
1976 +            ses.scheduleAtFixedRate((Runnable) null,
1977 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1978 +            shouldThrow();
1979 +        } catch (NullPointerException success) {}
1980 +        try {
1981 +            ses.scheduleWithFixedDelay((Runnable) null,
1982 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1983 +            shouldThrow();
1984 +        } catch (NullPointerException success) {}
1985 +    }
1986 +
1987 +    void setRejectedExecutionHandler(
1988 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1989 +        p.setRejectedExecutionHandler(handler);
1990 +        assertSame(handler, p.getRejectedExecutionHandler());
1991 +    }
1992 +
1993 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1994 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1995 +        final long savedTaskCount = p.getTaskCount();
1996 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1997 +        final int savedQueueSize = p.getQueue().size();
1998 +        final boolean stock = (p.getClass().getClassLoader() == null);
1999 +
2000 +        Runnable r = () -> {};
2001 +        Callable<Boolean> c = () -> Boolean.TRUE;
2002 +
2003 +        class Recorder implements RejectedExecutionHandler {
2004 +            public volatile Runnable r = null;
2005 +            public volatile ThreadPoolExecutor p = null;
2006 +            public void reset() { r = null; p = null; }
2007 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2008 +                assertNull(this.r);
2009 +                assertNull(this.p);
2010 +                this.r = r;
2011 +                this.p = p;
2012 +            }
2013 +        }
2014 +
2015 +        // check custom handler is invoked exactly once per task
2016 +        Recorder recorder = new Recorder();
2017 +        setRejectedExecutionHandler(p, recorder);
2018 +        for (int i = 2; i--> 0; ) {
2019 +            recorder.reset();
2020 +            p.execute(r);
2021 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2022 +                assertSame(r, recorder.r);
2023 +            assertSame(p, recorder.p);
2024 +
2025 +            recorder.reset();
2026 +            assertFalse(p.submit(r).isDone());
2027 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2028 +            assertSame(p, recorder.p);
2029 +
2030 +            recorder.reset();
2031 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2032 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2033 +            assertSame(p, recorder.p);
2034 +
2035 +            recorder.reset();
2036 +            assertFalse(p.submit(c).isDone());
2037 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2038 +            assertSame(p, recorder.p);
2039 +
2040 +            if (p instanceof ScheduledExecutorService) {
2041 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2042 +                ScheduledFuture<?> future;
2043 +
2044 +                recorder.reset();
2045 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2046 +                assertFalse(future.isDone());
2047 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2048 +                assertSame(p, recorder.p);
2049 +
2050 +                recorder.reset();
2051 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2052 +                assertFalse(future.isDone());
2053 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2054 +                assertSame(p, recorder.p);
2055 +
2056 +                recorder.reset();
2057 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2058 +                assertFalse(future.isDone());
2059 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2060 +                assertSame(p, recorder.p);
2061 +
2062 +                recorder.reset();
2063 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2064 +                assertFalse(future.isDone());
2065 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2066 +                assertSame(p, recorder.p);
2067 +            }
2068 +        }
2069 +
2070 +        // Checking our custom handler above should be sufficient, but
2071 +        // we add some integration tests of standard handlers.
2072 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2073 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2074 +
2075 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2076 +        try {
2077 +            p.execute(setThread);
2078 +            shouldThrow();
2079 +        } catch (RejectedExecutionException success) {}
2080 +        assertNull(thread.get());
2081 +
2082 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2083 +        p.execute(setThread);
2084 +        assertNull(thread.get());
2085 +
2086 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2087 +        p.execute(setThread);
2088 +        if (p.isShutdown())
2089 +            assertNull(thread.get());
2090 +        else
2091 +            assertSame(Thread.currentThread(), thread.get());
2092 +
2093 +        setRejectedExecutionHandler(p, savedHandler);
2094 +
2095 +        // check that pool was not perturbed by handlers
2096 +        assertEquals(savedTaskCount, p.getTaskCount());
2097 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2098 +        assertEquals(savedQueueSize, p.getQueue().size());
2099 +    }
2100   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines