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.176 by jsr166, Mon Oct 12 07:16:39 2015 UTC vs.
Revision 1.236 by jsr166, Wed Aug 16 17:18:34 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 112 | Line 154 | import junit.framework.TestSuite;
154   * methods as there are exceptions the method can throw. Sometimes
155   * there are multiple tests per JSR166 method when the different
156   * "normal" behaviors differ significantly. And sometimes testcases
157 < * cover multiple methods when they cannot be tested in
116 < * isolation.
157 > * cover multiple methods when they cannot be tested in isolation.
158   *
159   * <li>The documentation style for testcases is to provide as javadoc
160   * a simple sentence or two describing the property that the testcase
# Line 176 | 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 227 | 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 273 | Line 354 | public class JSR166TestCase extends Test
354          main(suite(), args);
355      }
356  
357 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
358 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
359 +        long runTime;
360 +        public void startTest(Test test) {}
361 +        protected void printHeader(long runTime) {
362 +            this.runTime = runTime; // defer printing for later
363 +        }
364 +        protected void printFooter(TestResult result) {
365 +            if (result.wasSuccessful()) {
366 +                getWriter().println("OK (" + result.runCount() + " tests)"
367 +                    + "  Time: " + elapsedTimeAsString(runTime));
368 +            } else {
369 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
370 +                super.printFooter(result);
371 +            }
372 +        }
373 +    }
374 +
375 +    /**
376 +     * Returns a TestRunner that doesn't bother with unnecessary
377 +     * fluff, like printing a "." for each test case.
378 +     */
379 +    static junit.textui.TestRunner newPithyTestRunner() {
380 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
381 +        runner.setPrinter(new PithyResultPrinter(System.out));
382 +        return runner;
383 +    }
384 +
385      /**
386       * Runs all unit tests in the given test suite.
387       * Actual behavior influenced by jsr166.* system properties.
# Line 284 | Line 393 | public class JSR166TestCase extends Test
393              System.setSecurityManager(new SecurityManager());
394          }
395          for (int i = 0; i < suiteRuns; i++) {
396 <            TestResult result = junit.textui.TestRunner.run(suite);
396 >            TestResult result = newPithyTestRunner().doRun(suite);
397              if (!result.wasSuccessful())
398                  System.exit(1);
399              System.gc();
# Line 368 | 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 390 | 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 418 | 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",
552                  "StampedLockTest",
553                  "SubmissionPublisherTest",
554                  "ThreadLocalRandom8Test",
555 +                "TimeUnit8Test",
556              };
557              addNamedTestClasses(suite, java8TestClassNames);
558          }
# Line 444 | Line 560 | public class JSR166TestCase extends Test
560          // Java9+ test classes
561          if (atLeastJava9()) {
562              String[] java9TestClassNames = {
563 <                // Currently empty, but expecting varhandle tests
563 >                "AtomicBoolean9Test",
564 >                "AtomicInteger9Test",
565 >                "AtomicIntegerArray9Test",
566 >                "AtomicLong9Test",
567 >                "AtomicLongArray9Test",
568 >                "AtomicReference9Test",
569 >                "AtomicReferenceArray9Test",
570 >                "ExecutorCompletionService9Test",
571 >                "ForkJoinPool9Test",
572              };
573              addNamedTestClasses(suite, java9TestClassNames);
574          }
# Line 455 | 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 520 | 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 could
676 <     * be reimplemented to use for example a Property.
675 >     * Returns the shortest timed delay. This can be scaled up for
676 >     * slow machines using the jsr166.delay.factor system property,
677 >     * or via jtreg's -timeoutFactor: flag.
678 >     * http://openjdk.java.net/jtreg/command-help.html
679       */
680      protected long getShortDelay() {
681 <        return 50;
681 >        return (long) (50 * delayFactor);
682      }
683  
684      /**
# Line 538 | 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 559 | 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 838 | Line 996 | public class JSR166TestCase extends Test
996          }};
997      }
998  
999 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1000 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
1001 +    }
1002 +
1003 +    Runnable releaser(final AtomicBoolean flag) {
1004 +        return new Runnable() { public void run() { flag.set(true); }};
1005 +    }
1006 +
1007      /**
1008       * Waits out termination of a thread pool or fails doing so.
1009       */
# Line 861 | Line 1027 | public class JSR166TestCase extends Test
1027          }
1028      }
1029  
1030 <    /** Like Runnable, but with the freedom to throw anything */
1030 >    /**
1031 >     * Like Runnable, but with the freedom to throw anything.
1032 >     * junit folks had the same idea:
1033 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1034 >     */
1035      interface Action { public void run() throws Throwable; }
1036  
1037      /**
# Line 892 | Line 1062 | public class JSR166TestCase extends Test
1062       * Uninteresting threads are filtered out.
1063       */
1064      static void dumpTestThreads() {
1065 +        SecurityManager sm = System.getSecurityManager();
1066 +        if (sm != null) {
1067 +            try {
1068 +                System.setSecurityManager(null);
1069 +            } catch (SecurityException giveUp) {
1070 +                return;
1071 +            }
1072 +        }
1073 +
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;
1091              System.err.print(info);
1092          }
1093          System.err.println("------ stacktrace dump end ------");
912    }
913
914    /**
915     * Checks that thread does not terminate within the default
916     * millisecond delay of {@code timeoutMillis()}.
917     */
918    void assertThreadStaysAlive(Thread thread) {
919        assertThreadStaysAlive(thread, timeoutMillis());
920    }
921
922    /**
923     * Checks that thread does not terminate within the given millisecond delay.
924     */
925    void assertThreadStaysAlive(Thread thread, long millis) {
926        try {
927            // No need to optimize the failing case via Thread.join.
928            delay(millis);
929            assertTrue(thread.isAlive());
930        } catch (InterruptedException fail) {
931            threadFail("Unexpected InterruptedException");
932        }
933    }
1094  
1095 <    /**
936 <     * Checks that the threads do not terminate within the default
937 <     * millisecond delay of {@code timeoutMillis()}.
938 <     */
939 <    void assertThreadsStayAlive(Thread... threads) {
940 <        assertThreadsStayAlive(timeoutMillis(), threads);
1095 >        if (sm != null) System.setSecurityManager(sm);
1096      }
1097  
1098      /**
1099 <     * Checks that the threads do not terminate within the given millisecond delay.
1099 >     * Checks that thread eventually enters the expected blocked thread state.
1100       */
1101 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1102 <        try {
1103 <            // No need to optimize the failing case via Thread.join.
1104 <            delay(millis);
1105 <            for (Thread thread : threads)
1106 <                assertTrue(thread.isAlive());
1107 <        } catch (InterruptedException fail) {
1108 <            threadFail("Unexpected InterruptedException");
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      /**
# Line 992 | Line 1153 | public class JSR166TestCase extends Test
1153      }
1154  
1155      /**
1156 +     * The maximum number of consecutive spurious wakeups we should
1157 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1158 +     */
1159 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1160 +
1161 +    /**
1162       * The number of elements to place in collections, arrays, etc.
1163       */
1164      public static final int SIZE = 20;
# Line 1095 | Line 1262 | public class JSR166TestCase extends Test
1262          }
1263          public void refresh() {}
1264          public String toString() {
1265 <            List<Permission> ps = new ArrayList<Permission>();
1265 >            List<Permission> ps = new ArrayList<>();
1266              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1267                  ps.add(e.nextElement());
1268              return "AdjustablePolicy with permissions " + ps;
# Line 1125 | Line 1292 | public class JSR166TestCase extends Test
1292       * Sleeps until the given time has elapsed.
1293       * Throws AssertionFailedError if interrupted.
1294       */
1295 <    void sleep(long millis) {
1295 >    static void sleep(long millis) {
1296          try {
1297              delay(millis);
1298          } catch (InterruptedException fail) {
# Line 1141 | Line 1308 | public class JSR166TestCase extends Test
1308       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1309       */
1310      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1311 <        long startTime = System.nanoTime();
1311 >        long startTime = 0L;
1312          for (;;) {
1313              Thread.State s = thread.getState();
1314              if (s == Thread.State.BLOCKED ||
# Line 1150 | Line 1317 | public class JSR166TestCase extends Test
1317                  return;
1318              else if (s == Thread.State.TERMINATED)
1319                  fail("Unexpected thread termination");
1320 +            else if (startTime == 0L)
1321 +                startTime = System.nanoTime();
1322              else if (millisElapsedSince(startTime) > timeoutMillis) {
1323                  threadAssertTrue(thread.isAlive());
1324 <                return;
1324 >                fail("timed out waiting for thread to enter wait state");
1325 >            }
1326 >            Thread.yield();
1327 >        }
1328 >    }
1329 >
1330 >    /**
1331 >     * Spin-waits up to the specified number of milliseconds for the given
1332 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1333 >     * and additionally satisfy the given condition.
1334 >     */
1335 >    void waitForThreadToEnterWaitState(
1336 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1337 >        long startTime = 0L;
1338 >        for (;;) {
1339 >            Thread.State s = thread.getState();
1340 >            if (s == Thread.State.BLOCKED ||
1341 >                s == Thread.State.WAITING ||
1342 >                s == Thread.State.TIMED_WAITING) {
1343 >                try {
1344 >                    if (waitingForGodot.call())
1345 >                        return;
1346 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1347 >            }
1348 >            else if (s == Thread.State.TERMINATED)
1349 >                fail("Unexpected thread termination");
1350 >            else if (startTime == 0L)
1351 >                startTime = System.nanoTime();
1352 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1353 >                threadAssertTrue(thread.isAlive());
1354 >                fail("timed out waiting for thread to enter wait state");
1355              }
1356              Thread.yield();
1357          }
1358      }
1359  
1360      /**
1361 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1362 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1361 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1362 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1363       */
1364      void waitForThreadToEnterWaitState(Thread thread) {
1365          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1366      }
1367  
1368      /**
1369 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1370 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1371 +     * and additionally satisfy the given condition.
1372 +     */
1373 +    void waitForThreadToEnterWaitState(
1374 +        Thread thread, Callable<Boolean> waitingForGodot) {
1375 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1376 +    }
1377 +
1378 +    /**
1379       * Returns the number of milliseconds since time given by
1380       * startNanoTime, which must have been previously returned from a
1381       * call to {@link System#nanoTime()}.
# Line 1228 | Line 1437 | public class JSR166TestCase extends Test
1437          } finally {
1438              if (t.getState() != Thread.State.TERMINATED) {
1439                  t.interrupt();
1440 <                threadFail("Test timed out");
1440 >                threadFail("timed out waiting for thread to terminate");
1441              }
1442          }
1443      }
# Line 1394 | Line 1603 | public class JSR166TestCase extends Test
1603          return new LatchAwaiter(latch);
1604      }
1605  
1606 <    public void await(CountDownLatch latch) {
1606 >    public void await(CountDownLatch latch, long timeoutMillis) {
1607          try {
1608 <            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1608 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1609                  fail("timed out waiting for CountDownLatch for "
1610 <                     + (LONG_DELAY_MS/1000) + " sec");
1610 >                     + (timeoutMillis/1000) + " sec");
1611          } catch (Throwable fail) {
1612              threadUnexpectedException(fail);
1613          }
1614      }
1615  
1616 +    public void await(CountDownLatch latch) {
1617 +        await(latch, LONG_DELAY_MS);
1618 +    }
1619 +
1620      public void await(Semaphore semaphore) {
1621          try {
1622              if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
# Line 1414 | Line 1627 | public class JSR166TestCase extends Test
1627          }
1628      }
1629  
1630 +    public void await(CyclicBarrier barrier) {
1631 +        try {
1632 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1633 +        } catch (Throwable fail) {
1634 +            threadUnexpectedException(fail);
1635 +        }
1636 +    }
1637 +
1638   //     /**
1639   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1640   //      */
# Line 1437 | Line 1658 | public class JSR166TestCase extends Test
1658          public String call() { throw new NullPointerException(); }
1659      }
1660  
1440    public static class CallableOne implements Callable<Integer> {
1441        public Integer call() { return one; }
1442    }
1443
1444    public class ShortRunnable extends CheckedRunnable {
1445        protected void realRun() throws Throwable {
1446            delay(SHORT_DELAY_MS);
1447        }
1448    }
1449
1450    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1451        protected void realRun() throws InterruptedException {
1452            delay(SHORT_DELAY_MS);
1453        }
1454    }
1455
1456    public class SmallRunnable extends CheckedRunnable {
1457        protected void realRun() throws Throwable {
1458            delay(SMALL_DELAY_MS);
1459        }
1460    }
1461
1661      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1662          protected void realRun() {
1663              try {
# Line 1467 | Line 1666 | public class JSR166TestCase extends Test
1666          }
1667      }
1668  
1470    public class SmallCallable extends CheckedCallable {
1471        protected Object realCall() throws InterruptedException {
1472            delay(SMALL_DELAY_MS);
1473            return Boolean.TRUE;
1474        }
1475    }
1476
1477    public class MediumRunnable extends CheckedRunnable {
1478        protected void realRun() throws Throwable {
1479            delay(MEDIUM_DELAY_MS);
1480        }
1481    }
1482
1483    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1484        protected void realRun() throws InterruptedException {
1485            delay(MEDIUM_DELAY_MS);
1486        }
1487    }
1488
1669      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1670          return new CheckedRunnable() {
1671              protected void realRun() {
# Line 1495 | Line 1675 | public class JSR166TestCase extends Test
1675              }};
1676      }
1677  
1498    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1499        protected void realRun() {
1500            try {
1501                delay(MEDIUM_DELAY_MS);
1502            } catch (InterruptedException ok) {}
1503        }
1504    }
1505
1506    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1507        protected void realRun() {
1508            try {
1509                delay(LONG_DELAY_MS);
1510            } catch (InterruptedException ok) {}
1511        }
1512    }
1513
1678      /**
1679       * For use as ThreadFactory in constructors
1680       */
# Line 1524 | Line 1688 | public class JSR166TestCase extends Test
1688          boolean isDone();
1689      }
1690  
1527    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1528        return new TrackedRunnable() {
1529                private volatile boolean done = false;
1530                public boolean isDone() { return done; }
1531                public void run() {
1532                    try {
1533                        delay(timeoutMillis);
1534                        done = true;
1535                    } catch (InterruptedException ok) {}
1536                }
1537            };
1538    }
1539
1540    public static class TrackedShortRunnable implements Runnable {
1541        public volatile boolean done = false;
1542        public void run() {
1543            try {
1544                delay(SHORT_DELAY_MS);
1545                done = true;
1546            } catch (InterruptedException ok) {}
1547        }
1548    }
1549
1550    public static class TrackedSmallRunnable implements Runnable {
1551        public volatile boolean done = false;
1552        public void run() {
1553            try {
1554                delay(SMALL_DELAY_MS);
1555                done = true;
1556            } catch (InterruptedException ok) {}
1557        }
1558    }
1559
1560    public static class TrackedMediumRunnable implements Runnable {
1561        public volatile boolean done = false;
1562        public void run() {
1563            try {
1564                delay(MEDIUM_DELAY_MS);
1565                done = true;
1566            } catch (InterruptedException ok) {}
1567        }
1568    }
1569
1570    public static class TrackedLongRunnable implements Runnable {
1571        public volatile boolean done = false;
1572        public void run() {
1573            try {
1574                delay(LONG_DELAY_MS);
1575                done = true;
1576            } catch (InterruptedException ok) {}
1577        }
1578    }
1579
1691      public static class TrackedNoOpRunnable implements Runnable {
1692          public volatile boolean done = false;
1693          public void run() {
# Line 1584 | Line 1695 | public class JSR166TestCase extends Test
1695          }
1696      }
1697  
1587    public static class TrackedCallable implements Callable {
1588        public volatile boolean done = false;
1589        public Object call() {
1590            try {
1591                delay(SMALL_DELAY_MS);
1592                done = true;
1593            } catch (InterruptedException ok) {}
1594            return Boolean.TRUE;
1595        }
1596    }
1597
1698      /**
1699       * Analog of CheckedRunnable for RecursiveAction
1700       */
# Line 1638 | Line 1738 | public class JSR166TestCase extends Test
1738       * A CyclicBarrier that uses timed await and fails with
1739       * AssertionFailedErrors instead of throwing checked exceptions.
1740       */
1741 <    public class CheckedBarrier extends CyclicBarrier {
1741 >    public static class CheckedBarrier extends CyclicBarrier {
1742          public CheckedBarrier(int parties) { super(parties); }
1743  
1744          public int await() {
# Line 1661 | Line 1761 | public class JSR166TestCase extends Test
1761              assertEquals(0, q.size());
1762              assertNull(q.peek());
1763              assertNull(q.poll());
1764 <            assertNull(q.poll(0, MILLISECONDS));
1764 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1765              assertEquals(q.toString(), "[]");
1766              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1767              assertFalse(q.iterator().hasNext());
# Line 1702 | Line 1802 | public class JSR166TestCase extends Test
1802          }
1803      }
1804  
1805 +    void assertImmutable(final Object o) {
1806 +        if (o instanceof Collection) {
1807 +            assertThrows(
1808 +                UnsupportedOperationException.class,
1809 +                new Runnable() { public void run() {
1810 +                        ((Collection) o).add(null);}});
1811 +        }
1812 +    }
1813 +
1814      @SuppressWarnings("unchecked")
1815      <T> T serialClone(T o) {
1816          try {
1817              ObjectInputStream ois = new ObjectInputStream
1818                  (new ByteArrayInputStream(serialBytes(o)));
1819              T clone = (T) ois.readObject();
1820 +            if (o == clone) assertImmutable(o);
1821              assertSame(o.getClass(), clone.getClass());
1822              return clone;
1823          } catch (Throwable fail) {
# Line 1716 | Line 1826 | public class JSR166TestCase extends Test
1826          }
1827      }
1828  
1829 +    /**
1830 +     * A version of serialClone that leaves error handling (for
1831 +     * e.g. NotSerializableException) up to the caller.
1832 +     */
1833 +    @SuppressWarnings("unchecked")
1834 +    <T> T serialClonePossiblyFailing(T o)
1835 +        throws ReflectiveOperationException, java.io.IOException {
1836 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1837 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1838 +        oos.writeObject(o);
1839 +        oos.flush();
1840 +        oos.close();
1841 +        ObjectInputStream ois = new ObjectInputStream
1842 +            (new ByteArrayInputStream(bos.toByteArray()));
1843 +        T clone = (T) ois.readObject();
1844 +        if (o == clone) assertImmutable(o);
1845 +        assertSame(o.getClass(), clone.getClass());
1846 +        return clone;
1847 +    }
1848 +
1849 +    /**
1850 +     * If o implements Cloneable and has a public clone method,
1851 +     * returns a clone of o, else null.
1852 +     */
1853 +    @SuppressWarnings("unchecked")
1854 +    <T> T cloneableClone(T o) {
1855 +        if (!(o instanceof Cloneable)) return null;
1856 +        final T clone;
1857 +        try {
1858 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1859 +        } catch (NoSuchMethodException ok) {
1860 +            return null;
1861 +        } catch (ReflectiveOperationException unexpected) {
1862 +            throw new Error(unexpected);
1863 +        }
1864 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1865 +        assertSame(o.getClass(), clone.getClass());
1866 +        return clone;
1867 +    }
1868 +
1869      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1870                               Runnable... throwingActions) {
1871          for (Runnable throwingAction : throwingActions) {
# Line 1744 | Line 1894 | public class JSR166TestCase extends Test
1894          } catch (NoSuchElementException success) {}
1895          assertFalse(it.hasNext());
1896      }
1897 +
1898 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1899 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1900 +    }
1901 +
1902 +    public Runnable runnableThrowing(final RuntimeException ex) {
1903 +        return new Runnable() { public void run() { throw ex; }};
1904 +    }
1905 +
1906 +    /** A reusable thread pool to be shared by tests. */
1907 +    static final ExecutorService cachedThreadPool =
1908 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1909 +                               1000L, MILLISECONDS,
1910 +                               new SynchronousQueue<Runnable>());
1911 +
1912 +    static <T> void shuffle(T[] array) {
1913 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1914 +    }
1915 +
1916 +    /**
1917 +     * Returns the same String as would be returned by {@link
1918 +     * Object#toString}, whether or not the given object's class
1919 +     * overrides toString().
1920 +     *
1921 +     * @see System#identityHashCode
1922 +     */
1923 +    static String identityString(Object x) {
1924 +        return x.getClass().getName()
1925 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1926 +    }
1927 +
1928 +    // --- Shared assertions for Executor tests ---
1929 +
1930 +    /**
1931 +     * Returns maximum number of tasks that can be submitted to given
1932 +     * pool (with bounded queue) before saturation (when submission
1933 +     * throws RejectedExecutionException).
1934 +     */
1935 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1936 +        BlockingQueue<Runnable> q = pool.getQueue();
1937 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1938 +    }
1939 +
1940 +    @SuppressWarnings("FutureReturnValueIgnored")
1941 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1942 +        try {
1943 +            e.execute((Runnable) null);
1944 +            shouldThrow();
1945 +        } catch (NullPointerException success) {}
1946 +
1947 +        if (! (e instanceof ExecutorService)) return;
1948 +        ExecutorService es = (ExecutorService) e;
1949 +        try {
1950 +            es.submit((Runnable) null);
1951 +            shouldThrow();
1952 +        } catch (NullPointerException success) {}
1953 +        try {
1954 +            es.submit((Runnable) null, Boolean.TRUE);
1955 +            shouldThrow();
1956 +        } catch (NullPointerException success) {}
1957 +        try {
1958 +            es.submit((Callable) null);
1959 +            shouldThrow();
1960 +        } catch (NullPointerException success) {}
1961 +
1962 +        if (! (e instanceof ScheduledExecutorService)) return;
1963 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1964 +        try {
1965 +            ses.schedule((Runnable) null,
1966 +                         randomTimeout(), randomTimeUnit());
1967 +            shouldThrow();
1968 +        } catch (NullPointerException success) {}
1969 +        try {
1970 +            ses.schedule((Callable) null,
1971 +                         randomTimeout(), randomTimeUnit());
1972 +            shouldThrow();
1973 +        } catch (NullPointerException success) {}
1974 +        try {
1975 +            ses.scheduleAtFixedRate((Runnable) null,
1976 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1977 +            shouldThrow();
1978 +        } catch (NullPointerException success) {}
1979 +        try {
1980 +            ses.scheduleWithFixedDelay((Runnable) null,
1981 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1982 +            shouldThrow();
1983 +        } catch (NullPointerException success) {}
1984 +    }
1985 +
1986 +    void setRejectedExecutionHandler(
1987 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1988 +        p.setRejectedExecutionHandler(handler);
1989 +        assertSame(handler, p.getRejectedExecutionHandler());
1990 +    }
1991 +
1992 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1993 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1994 +        final long savedTaskCount = p.getTaskCount();
1995 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1996 +        final int savedQueueSize = p.getQueue().size();
1997 +        final boolean stock = (p.getClass().getClassLoader() == null);
1998 +
1999 +        Runnable r = () -> {};
2000 +        Callable<Boolean> c = () -> Boolean.TRUE;
2001 +
2002 +        class Recorder implements RejectedExecutionHandler {
2003 +            public volatile Runnable r = null;
2004 +            public volatile ThreadPoolExecutor p = null;
2005 +            public void reset() { r = null; p = null; }
2006 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2007 +                assertNull(this.r);
2008 +                assertNull(this.p);
2009 +                this.r = r;
2010 +                this.p = p;
2011 +            }
2012 +        }
2013 +
2014 +        // check custom handler is invoked exactly once per task
2015 +        Recorder recorder = new Recorder();
2016 +        setRejectedExecutionHandler(p, recorder);
2017 +        for (int i = 2; i--> 0; ) {
2018 +            recorder.reset();
2019 +            p.execute(r);
2020 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2021 +                assertSame(r, recorder.r);
2022 +            assertSame(p, recorder.p);
2023 +
2024 +            recorder.reset();
2025 +            assertFalse(p.submit(r).isDone());
2026 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2027 +            assertSame(p, recorder.p);
2028 +
2029 +            recorder.reset();
2030 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2031 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2032 +            assertSame(p, recorder.p);
2033 +
2034 +            recorder.reset();
2035 +            assertFalse(p.submit(c).isDone());
2036 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2037 +            assertSame(p, recorder.p);
2038 +
2039 +            if (p instanceof ScheduledExecutorService) {
2040 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2041 +                ScheduledFuture<?> future;
2042 +
2043 +                recorder.reset();
2044 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2045 +                assertFalse(future.isDone());
2046 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2047 +                assertSame(p, recorder.p);
2048 +
2049 +                recorder.reset();
2050 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2051 +                assertFalse(future.isDone());
2052 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2053 +                assertSame(p, recorder.p);
2054 +
2055 +                recorder.reset();
2056 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2057 +                assertFalse(future.isDone());
2058 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2059 +                assertSame(p, recorder.p);
2060 +
2061 +                recorder.reset();
2062 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2063 +                assertFalse(future.isDone());
2064 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2065 +                assertSame(p, recorder.p);
2066 +            }
2067 +        }
2068 +
2069 +        // Checking our custom handler above should be sufficient, but
2070 +        // we add some integration tests of standard handlers.
2071 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2072 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2073 +
2074 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2075 +        try {
2076 +            p.execute(setThread);
2077 +            shouldThrow();
2078 +        } catch (RejectedExecutionException success) {}
2079 +        assertNull(thread.get());
2080 +
2081 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2082 +        p.execute(setThread);
2083 +        assertNull(thread.get());
2084 +
2085 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2086 +        p.execute(setThread);
2087 +        if (p.isShutdown())
2088 +            assertNull(thread.get());
2089 +        else
2090 +            assertSame(Thread.currentThread(), thread.get());
2091 +
2092 +        setRejectedExecutionHandler(p, savedHandler);
2093 +
2094 +        // check that pool was not perturbed by handlers
2095 +        assertEquals(savedTaskCount, p.getTaskCount());
2096 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2097 +        assertEquals(savedQueueSize, p.getQueue().size());
2098 +    }
2099   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines