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.182 by jsr166, Sun Jan 17 00:07:51 2016 UTC vs.
Revision 1.274 by dl, Tue Mar 22 16:26:19 2022 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
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;
# Line 22 | Line 49 | import java.io.ByteArrayOutputStream;
49   import java.io.ObjectInputStream;
50   import java.io.ObjectOutputStream;
51   import java.lang.management.ManagementFactory;
52 + import java.lang.management.LockInfo;
53   import java.lang.management.ThreadInfo;
54   import java.lang.management.ThreadMXBean;
55   import java.lang.reflect.Constructor;
56   import java.lang.reflect.Method;
57   import java.lang.reflect.Modifier;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
58   import java.security.CodeSource;
59   import java.security.Permission;
60   import java.security.PermissionCollection;
# Line 38 | Line 64 | import java.security.ProtectionDomain;
64   import java.security.SecurityPermission;
65   import java.util.ArrayList;
66   import java.util.Arrays;
67 + import java.util.Collection;
68 + import java.util.Collections;
69   import java.util.Date;
70 + import java.util.Deque;
71   import java.util.Enumeration;
72 + import java.util.HashSet;
73   import java.util.Iterator;
74   import java.util.List;
75   import java.util.NoSuchElementException;
76   import java.util.PropertyPermission;
77 + import java.util.Queue;
78 + import java.util.Set;
79   import java.util.concurrent.BlockingQueue;
80   import java.util.concurrent.Callable;
81   import java.util.concurrent.CountDownLatch;
82   import java.util.concurrent.CyclicBarrier;
83   import java.util.concurrent.ExecutionException;
84 + import java.util.concurrent.Executor;
85   import java.util.concurrent.Executors;
86   import java.util.concurrent.ExecutorService;
87   import java.util.concurrent.ForkJoinPool;
88   import java.util.concurrent.Future;
89 + import java.util.concurrent.FutureTask;
90   import java.util.concurrent.RecursiveAction;
91   import java.util.concurrent.RecursiveTask;
92 + import java.util.concurrent.RejectedExecutionException;
93   import java.util.concurrent.RejectedExecutionHandler;
94   import java.util.concurrent.Semaphore;
95 + import java.util.concurrent.ScheduledExecutorService;
96 + import java.util.concurrent.ScheduledFuture;
97 + import java.util.concurrent.SynchronousQueue;
98   import java.util.concurrent.ThreadFactory;
99 + import java.util.concurrent.ThreadLocalRandom;
100   import java.util.concurrent.ThreadPoolExecutor;
101 + import java.util.concurrent.TimeUnit;
102   import java.util.concurrent.TimeoutException;
103 + import java.util.concurrent.atomic.AtomicBoolean;
104   import java.util.concurrent.atomic.AtomicReference;
64 import java.util.regex.Matcher;
105   import java.util.regex.Pattern;
106  
67 import junit.framework.AssertionFailedError;
107   import junit.framework.Test;
108   import junit.framework.TestCase;
109   import junit.framework.TestResult;
# Line 80 | Line 119 | import junit.framework.TestSuite;
119   *
120   * <ol>
121   *
122 < * <li>All assertions in code running in generated threads must use
123 < * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
124 < * #threadAssertEquals}, or {@link #threadAssertNull}, (not
125 < * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
126 < * particularly recommended) for other code to use these forms too.
127 < * Only the most typically used JUnit assertion methods are defined
128 < * this way, but enough to live with.
122 > * <li>All code not running in the main test thread (manually spawned threads
123 > * or the common fork join pool) must be checked for failure (and completion!).
124 > * Mechanisms that can be used to ensure this are:
125 > *   <ol>
126 > *   <li>Signalling via a synchronizer like AtomicInteger or CountDownLatch
127 > *    that the task completed normally, which is checked before returning from
128 > *    the test method in the main thread.
129 > *   <li>Using the forms {@link #threadFail}, {@link #threadAssertTrue},
130 > *    or {@link #threadAssertNull}, (not {@code fail}, {@code assertTrue}, etc.)
131 > *    Only the most typically used JUnit assertion methods are defined
132 > *    this way, but enough to live with.
133 > *   <li>Recording failure explicitly using {@link #threadUnexpectedException}
134 > *    or {@link #threadRecordFailure}.
135 > *   <li>Using a wrapper like CheckedRunnable that uses one the mechanisms above.
136 > *   </ol>
137   *
138   * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
139   * to invoke {@code super.setUp} and {@code super.tearDown} within
# Line 104 | Line 151 | import junit.framework.TestSuite;
151   * but even so, if there is ever any doubt, they can all be increased
152   * in one spot to rerun tests on slower platforms.
153   *
154 + * Class Item is used for elements of collections and related
155 + * purposes. Many tests rely on their keys being equal to ints. To
156 + * check these, methods mustEqual, mustContain, etc adapt the JUnit
157 + * assert methods to intercept ints.
158 + *
159   * <li>All threads generated must be joined inside each test case
160   * method (or {@code fail} to do so) before returning from the
161   * method. The {@code joinPool} method can be used to do this when
# Line 143 | Line 195 | import junit.framework.TestSuite;
195   * </ul>
196   */
197   public class JSR166TestCase extends TestCase {
198 +    // No longer run with custom securityManagers
199      private static final boolean useSecurityManager =
200 <        Boolean.getBoolean("jsr166.useSecurityManager");
200 >    Boolean.getBoolean("jsr166.useSecurityManager");
201  
202      protected static final boolean expensiveTests =
203          Boolean.getBoolean("jsr166.expensiveTests");
# Line 183 | Line 236 | public class JSR166TestCase extends Test
236          Integer.getInteger("jsr166.suiteRuns", 1);
237  
238      /**
239 <     * The scaling factor to apply to standard delays used in tests.
239 >     * Returns the value of the system property, or NaN if not defined.
240       */
241 <    private static final int delayFactor =
242 <        Integer.getInteger("jsr166.delay.factor", 1);
241 >    private static float systemPropertyValue(String name) {
242 >        String floatString = System.getProperty(name);
243 >        if (floatString == null)
244 >            return Float.NaN;
245 >        try {
246 >            return Float.parseFloat(floatString);
247 >        } catch (NumberFormatException ex) {
248 >            throw new IllegalArgumentException(
249 >                String.format("Bad float value in system property %s=%s",
250 >                              name, floatString));
251 >        }
252 >    }
253 >
254 >    private static final ThreadMXBean THREAD_MXBEAN
255 >        = ManagementFactory.getThreadMXBean();
256 >
257 >    /**
258 >     * The scaling factor to apply to standard delays used in tests.
259 >     * May be initialized from any of:
260 >     * - the "jsr166.delay.factor" system property
261 >     * - the "test.timeout.factor" system property (as used by jtreg)
262 >     *   See: http://openjdk.java.net/jtreg/tag-spec.html
263 >     * - hard-coded fuzz factor when using a known slowpoke VM
264 >     */
265 >    private static final float delayFactor = delayFactor();
266 >
267 >    private static float delayFactor() {
268 >        float x;
269 >        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
270 >            return x;
271 >        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
272 >            return x;
273 >        String prop = System.getProperty("java.vm.version");
274 >        if (prop != null && prop.matches(".*debug.*"))
275 >            return 4.0f; // How much slower is fastdebug than product?!
276 >        return 1.0f;
277 >    }
278  
279      public JSR166TestCase() { super(); }
280      public JSR166TestCase(String name) { super(name); }
# Line 207 | Line 295 | public class JSR166TestCase extends Test
295      static volatile TestCase currentTestCase;
296      // static volatile int currentRun = 0;
297      static {
298 <        Runnable checkForWedgedTest = new Runnable() { public void run() {
298 >        Runnable wedgedTestDetector = new Runnable() { public void run() {
299              // Avoid spurious reports with enormous runsPerTest.
300              // A single test case run should never take more than 1 second.
301              // But let's cap it at the high end too ...
302 <            final int timeoutMinutes =
303 <                Math.min(15, Math.max(runsPerTest / 60, 1));
302 >            final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1)
303 >                * Math.max((int) delayFactor, 1);
304 >            final int timeoutMinutes = Math.min(15, timeoutMinutesMin);
305              for (TestCase lastTestCase = currentTestCase;;) {
306                  try { MINUTES.sleep(timeoutMinutes); }
307                  catch (InterruptedException unexpected) { break; }
# Line 232 | Line 321 | public class JSR166TestCase extends Test
321                  }
322                  lastTestCase = currentTestCase;
323              }}};
324 <        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
324 >        Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector");
325          thread.setDaemon(true);
326          thread.start();
327      }
328  
329   //     public static String cpuModel() {
330   //         try {
331 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
331 > //             java.util.regex.Matcher matcher
332 > //               = Pattern.compile("model name\\s*: (.*)")
333   //                 .matcher(new String(
334 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
334 > //                     java.nio.file.Files.readAllBytes(
335 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
336   //             matcher.find();
337   //             return matcher.group(1);
338   //         } catch (Exception ex) { return null; }
# Line 274 | Line 365 | public class JSR166TestCase extends Test
365              // Never report first run of any test; treat it as a
366              // warmup run, notably to trigger all needed classloading,
367              if (i > 0)
368 <                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
368 >                System.out.printf("%s: %d%n", toString(), elapsedMillis);
369          }
370      }
371  
# Line 317 | Line 408 | public class JSR166TestCase extends Test
408       * Runs all unit tests in the given test suite.
409       * Actual behavior influenced by jsr166.* system properties.
410       */
411 +    @SuppressWarnings("removal")
412      static void main(Test suite, String[] args) {
413          if (useSecurityManager) {
414              System.err.println("Setting a permissive security manager");
# Line 350 | Line 442 | public class JSR166TestCase extends Test
442          for (String testClassName : testClassNames) {
443              try {
444                  Class<?> testClass = Class.forName(testClassName);
445 <                Method m = testClass.getDeclaredMethod("suite",
354 <                                                       new Class<?>[0]);
445 >                Method m = testClass.getDeclaredMethod("suite");
446                  suite.addTest(newTestSuite((Test)m.invoke(null)));
447 <            } catch (Exception e) {
448 <                throw new Error("Missing test class", e);
447 >            } catch (ReflectiveOperationException e) {
448 >                throw new AssertionError("Missing test class", e);
449              }
450          }
451      }
# Line 363 | Line 454 | public class JSR166TestCase extends Test
454      public static final String JAVA_SPECIFICATION_VERSION;
455      static {
456          try {
457 <            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
457 >            @SuppressWarnings("removal") double jcv =
458 >            java.security.AccessController.doPrivileged(
459                  new java.security.PrivilegedAction<Double>() {
460                  public Double run() {
461                      return Double.valueOf(System.getProperty("java.class.version"));}});
462 <            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
462 >            JAVA_CLASS_VERSION = jcv;
463 >            @SuppressWarnings("removal") String jsv =
464 >            java.security.AccessController.doPrivileged(
465                  new java.security.PrivilegedAction<String>() {
466                  public String run() {
467                      return System.getProperty("java.specification.version");}});
468 +            JAVA_SPECIFICATION_VERSION = jsv;
469          } catch (Throwable t) {
470              throw new Error(t);
471          }
472      }
473  
474 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
475 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
476 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
477 <    public static boolean atLeastJava9() {
478 <        return JAVA_CLASS_VERSION >= 53.0
479 <            // As of 2015-09, java9 still uses 52.0 class file version
480 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
481 <    }
482 <    public static boolean atLeastJava10() {
483 <        return JAVA_CLASS_VERSION >= 54.0
484 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
485 <    }
474 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
475 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
476 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
477 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
478 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
479 >    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
480 >    public static boolean atLeastJava12() { return JAVA_CLASS_VERSION >= 56.0; }
481 >    public static boolean atLeastJava13() { return JAVA_CLASS_VERSION >= 57.0; }
482 >    public static boolean atLeastJava14() { return JAVA_CLASS_VERSION >= 58.0; }
483 >    public static boolean atLeastJava15() { return JAVA_CLASS_VERSION >= 59.0; }
484 >    public static boolean atLeastJava16() { return JAVA_CLASS_VERSION >= 60.0; }
485 >    public static boolean atLeastJava17() { return JAVA_CLASS_VERSION >= 61.0; }
486  
487      /**
488       * Collects all JSR166 unit tests as one suite.
# Line 408 | Line 503 | public class JSR166TestCase extends Test
503              AbstractQueuedLongSynchronizerTest.suite(),
504              ArrayBlockingQueueTest.suite(),
505              ArrayDequeTest.suite(),
506 +            ArrayListTest.suite(),
507              AtomicBooleanTest.suite(),
508              AtomicIntegerArrayTest.suite(),
509              AtomicIntegerFieldUpdaterTest.suite(),
# Line 430 | Line 526 | public class JSR166TestCase extends Test
526              CopyOnWriteArrayListTest.suite(),
527              CopyOnWriteArraySetTest.suite(),
528              CountDownLatchTest.suite(),
529 +            CountedCompleterTest.suite(),
530              CyclicBarrierTest.suite(),
531              DelayQueueTest.suite(),
532              EntryTest.suite(),
# Line 437 | Line 534 | public class JSR166TestCase extends Test
534              ExecutorsTest.suite(),
535              ExecutorCompletionServiceTest.suite(),
536              FutureTaskTest.suite(),
537 +            HashtableTest.suite(),
538              LinkedBlockingDequeTest.suite(),
539              LinkedBlockingQueueTest.suite(),
540              LinkedListTest.suite(),
# Line 458 | Line 556 | public class JSR166TestCase extends Test
556              TreeMapTest.suite(),
557              TreeSetTest.suite(),
558              TreeSubMapTest.suite(),
559 <            TreeSubSetTest.suite());
559 >            TreeSubSetTest.suite(),
560 >            VectorTest.suite());
561  
562          // Java8+ test classes
563          if (atLeastJava8()) {
564              String[] java8TestClassNames = {
565 +                "ArrayDeque8Test",
566                  "Atomic8Test",
567                  "CompletableFutureTest",
568                  "ConcurrentHashMap8Test",
569 <                "CountedCompleterTest",
569 >                "CountedCompleter8Test",
570                  "DoubleAccumulatorTest",
571                  "DoubleAdderTest",
572                  "ForkJoinPool8Test",
573                  "ForkJoinTask8Test",
574 +                "HashMapTest",
575 +                "LinkedBlockingDeque8Test",
576 +                "LinkedBlockingQueue8Test",
577 +                "LinkedHashMapTest",
578                  "LongAccumulatorTest",
579                  "LongAdderTest",
580                  "SplittableRandomTest",
581                  "StampedLockTest",
582                  "SubmissionPublisherTest",
583                  "ThreadLocalRandom8Test",
584 +                "TimeUnit8Test",
585              };
586              addNamedTestClasses(suite, java8TestClassNames);
587          }
# Line 484 | Line 589 | public class JSR166TestCase extends Test
589          // Java9+ test classes
590          if (atLeastJava9()) {
591              String[] java9TestClassNames = {
592 <                // Currently empty, but expecting varhandle tests
592 >                "AtomicBoolean9Test",
593 >                "AtomicInteger9Test",
594 >                "AtomicIntegerArray9Test",
595 >                "AtomicLong9Test",
596 >                "AtomicLongArray9Test",
597 >                "AtomicReference9Test",
598 >                "AtomicReferenceArray9Test",
599 >                "ExecutorCompletionService9Test",
600 >                "ForkJoinPool9Test",
601              };
602              addNamedTestClasses(suite, java9TestClassNames);
603          }
604  
605 +        if (atLeastJava17()) {
606 +            String[] java17TestClassNames = {
607 +                "ForkJoinPool19Test",
608 +            };
609 +            addNamedTestClasses(suite, java17TestClassNames);
610 +        }
611          return suite;
612      }
613  
614      /** Returns list of junit-style test method names in given class. */
615      public static ArrayList<String> testMethodNames(Class<?> testClass) {
616          Method[] methods = testClass.getDeclaredMethods();
617 <        ArrayList<String> names = new ArrayList<String>(methods.length);
617 >        ArrayList<String> names = new ArrayList<>(methods.length);
618          for (Method method : methods) {
619              if (method.getName().startsWith("test")
620                  && Modifier.isPublic(method.getModifiers())
# Line 522 | Line 641 | public class JSR166TestCase extends Test
641              for (String methodName : testMethodNames(testClass))
642                  suite.addTest((Test) c.newInstance(data, methodName));
643              return suite;
644 <        } catch (Exception e) {
645 <            throw new Error(e);
644 >        } catch (ReflectiveOperationException e) {
645 >            throw new AssertionError(e);
646          }
647      }
648  
# Line 539 | Line 658 | public class JSR166TestCase extends Test
658          if (atLeastJava8()) {
659              String name = testClass.getName();
660              String name8 = name.replaceAll("Test$", "8Test");
661 <            if (name.equals(name8)) throw new Error(name);
661 >            if (name.equals(name8)) throw new AssertionError(name);
662              try {
663                  return (Test)
664                      Class.forName(name8)
665 <                    .getMethod("testSuite", new Class[] { dataClass })
665 >                    .getMethod("testSuite", dataClass)
666                      .invoke(null, data);
667 <            } catch (Exception e) {
668 <                throw new Error(e);
667 >            } catch (ReflectiveOperationException e) {
668 >                throw new AssertionError(e);
669              }
670          } else {
671              return new TestSuite();
# Line 561 | Line 680 | public class JSR166TestCase extends Test
680      public static long LONG_DELAY_MS;
681  
682      /**
683 +     * A delay significantly longer than LONG_DELAY_MS.
684 +     * Use this in a thread that is waited for via awaitTermination(Thread).
685 +     */
686 +    public static long LONGER_DELAY_MS;
687 +
688 +    private static final long RANDOM_TIMEOUT;
689 +    private static final long RANDOM_EXPIRED_TIMEOUT;
690 +    private static final TimeUnit RANDOM_TIMEUNIT;
691 +    static {
692 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
693 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
694 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
695 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
696 +        TimeUnit[] timeUnits = TimeUnit.values();
697 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
698 +    }
699 +
700 +    /**
701 +     * Returns a timeout for use when any value at all will do.
702 +     */
703 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
704 +
705 +    /**
706 +     * Returns a timeout that means "no waiting", i.e. not positive.
707 +     */
708 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
709 +
710 +    /**
711 +     * Returns a random non-null TimeUnit.
712 +     */
713 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
714 +
715 +    /**
716 +     * Returns a random boolean; a "coin flip".
717 +     */
718 +    static boolean randomBoolean() {
719 +        return ThreadLocalRandom.current().nextBoolean();
720 +    }
721 +
722 +    /**
723 +     * Returns a random element from given choices.
724 +     */
725 +    <T> T chooseRandomly(List<T> choices) {
726 +        return choices.get(ThreadLocalRandom.current().nextInt(choices.size()));
727 +    }
728 +
729 +    /**
730 +     * Returns a random element from given choices.
731 +     */
732 +    @SuppressWarnings("unchecked")
733 +    <T> T chooseRandomly(T... choices) {
734 +        return choices[ThreadLocalRandom.current().nextInt(choices.length)];
735 +    }
736 +
737 +    /**
738       * Returns the shortest timed delay. This can be scaled up for
739 <     * slow machines using the jsr166.delay.factor system property.
739 >     * slow machines using the jsr166.delay.factor system property,
740 >     * or via jtreg's -timeoutFactor: flag.
741 >     * http://openjdk.java.net/jtreg/command-help.html
742       */
743      protected long getShortDelay() {
744 <        return 50 * delayFactor;
744 >        return (long) (50 * delayFactor);
745      }
746  
747      /**
# Line 576 | Line 752 | public class JSR166TestCase extends Test
752          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
753          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
754          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
755 +        LONGER_DELAY_MS = 2 * LONG_DELAY_MS;
756      }
757  
758 +    private static final long TIMEOUT_DELAY_MS
759 +        = (long) (12.0 * Math.cbrt(delayFactor));
760 +
761      /**
762 <     * Returns a timeout in milliseconds to be used in tests that
763 <     * verify that operations block or time out.
762 >     * Returns a timeout in milliseconds to be used in tests that verify
763 >     * that operations block or time out.  We want this to be longer
764 >     * than the OS scheduling quantum, but not too long, so don't scale
765 >     * linearly with delayFactor; we use "crazy" cube root instead.
766       */
767 <    long timeoutMillis() {
768 <        return SHORT_DELAY_MS / 4;
767 >    static long timeoutMillis() {
768 >        return TIMEOUT_DELAY_MS;
769      }
770  
771      /**
# Line 599 | Line 781 | public class JSR166TestCase extends Test
781       * The first exception encountered if any threadAssertXXX method fails.
782       */
783      private final AtomicReference<Throwable> threadFailure
784 <        = new AtomicReference<Throwable>(null);
784 >        = new AtomicReference<>(null);
785  
786      /**
787       * Records an exception so that it can be rethrown later in the test
# Line 609 | Line 791 | public class JSR166TestCase extends Test
791       */
792      public void threadRecordFailure(Throwable t) {
793          System.err.println(t);
794 <        dumpTestThreads();
795 <        threadFailure.compareAndSet(null, t);
794 >        if (threadFailure.compareAndSet(null, t))
795 >            dumpTestThreads();
796      }
797  
798      public void setUp() {
# Line 621 | Line 803 | public class JSR166TestCase extends Test
803          String msg = toString() + ": " + String.format(format, args);
804          System.err.println(msg);
805          dumpTestThreads();
806 <        throw new AssertionFailedError(msg);
806 >        throw new AssertionError(msg);
807      }
808  
809      /**
# Line 642 | Line 824 | public class JSR166TestCase extends Test
824                  throw (RuntimeException) t;
825              else if (t instanceof Exception)
826                  throw (Exception) t;
827 <            else {
828 <                AssertionFailedError afe =
647 <                    new AssertionFailedError(t.toString());
648 <                afe.initCause(t);
649 <                throw afe;
650 <            }
827 >            else
828 >                throw new AssertionError(t.toString(), t);
829          }
830  
831          if (Thread.interrupted())
# Line 681 | Line 859 | public class JSR166TestCase extends Test
859  
860      /**
861       * Just like fail(reason), but additionally recording (using
862 <     * threadRecordFailure) any AssertionFailedError thrown, so that
863 <     * the current testcase will fail.
862 >     * threadRecordFailure) any AssertionError thrown, so that the
863 >     * current testcase will fail.
864       */
865      public void threadFail(String reason) {
866          try {
867              fail(reason);
868 <        } catch (AssertionFailedError t) {
869 <            threadRecordFailure(t);
870 <            throw t;
868 >        } catch (AssertionError fail) {
869 >            threadRecordFailure(fail);
870 >            throw fail;
871          }
872      }
873  
874      /**
875       * Just like assertTrue(b), but additionally recording (using
876 <     * threadRecordFailure) any AssertionFailedError thrown, so that
877 <     * the current testcase will fail.
876 >     * threadRecordFailure) any AssertionError thrown, so that the
877 >     * current testcase will fail.
878       */
879      public void threadAssertTrue(boolean b) {
880          try {
881              assertTrue(b);
882 <        } catch (AssertionFailedError t) {
883 <            threadRecordFailure(t);
884 <            throw t;
882 >        } catch (AssertionError fail) {
883 >            threadRecordFailure(fail);
884 >            throw fail;
885          }
886      }
887  
888      /**
889       * Just like assertFalse(b), but additionally recording (using
890 <     * threadRecordFailure) any AssertionFailedError thrown, so that
891 <     * the current testcase will fail.
890 >     * threadRecordFailure) any AssertionError thrown, so that the
891 >     * current testcase will fail.
892       */
893      public void threadAssertFalse(boolean b) {
894          try {
895              assertFalse(b);
896 <        } catch (AssertionFailedError t) {
897 <            threadRecordFailure(t);
898 <            throw t;
896 >        } catch (AssertionError fail) {
897 >            threadRecordFailure(fail);
898 >            throw fail;
899          }
900      }
901  
902      /**
903       * Just like assertNull(x), but additionally recording (using
904 <     * threadRecordFailure) any AssertionFailedError thrown, so that
905 <     * the current testcase will fail.
904 >     * threadRecordFailure) any AssertionError thrown, so that the
905 >     * current testcase will fail.
906       */
907      public void threadAssertNull(Object x) {
908          try {
909              assertNull(x);
910 <        } catch (AssertionFailedError t) {
911 <            threadRecordFailure(t);
912 <            throw t;
910 >        } catch (AssertionError fail) {
911 >            threadRecordFailure(fail);
912 >            throw fail;
913          }
914      }
915  
916      /**
917       * Just like assertEquals(x, y), but additionally recording (using
918 <     * threadRecordFailure) any AssertionFailedError thrown, so that
919 <     * the current testcase will fail.
918 >     * threadRecordFailure) any AssertionError thrown, so that the
919 >     * current testcase will fail.
920       */
921      public void threadAssertEquals(long x, long y) {
922          try {
923              assertEquals(x, y);
924 <        } catch (AssertionFailedError t) {
925 <            threadRecordFailure(t);
926 <            throw t;
924 >        } catch (AssertionError fail) {
925 >            threadRecordFailure(fail);
926 >            throw fail;
927          }
928      }
929  
930      /**
931       * Just like assertEquals(x, y), but additionally recording (using
932 <     * threadRecordFailure) any AssertionFailedError thrown, so that
933 <     * the current testcase will fail.
932 >     * threadRecordFailure) any AssertionError thrown, so that the
933 >     * current testcase will fail.
934       */
935      public void threadAssertEquals(Object x, Object y) {
936          try {
937              assertEquals(x, y);
938 <        } catch (AssertionFailedError fail) {
938 >        } catch (AssertionError fail) {
939              threadRecordFailure(fail);
940              throw fail;
941          } catch (Throwable fail) {
# Line 767 | Line 945 | public class JSR166TestCase extends Test
945  
946      /**
947       * Just like assertSame(x, y), but additionally recording (using
948 <     * threadRecordFailure) any AssertionFailedError thrown, so that
949 <     * the current testcase will fail.
948 >     * threadRecordFailure) any AssertionError thrown, so that the
949 >     * current testcase will fail.
950       */
951      public void threadAssertSame(Object x, Object y) {
952          try {
953              assertSame(x, y);
954 <        } catch (AssertionFailedError fail) {
954 >        } catch (AssertionError fail) {
955              threadRecordFailure(fail);
956              throw fail;
957          }
# Line 795 | Line 973 | public class JSR166TestCase extends Test
973  
974      /**
975       * Records the given exception using {@link #threadRecordFailure},
976 <     * then rethrows the exception, wrapping it in an
977 <     * AssertionFailedError if necessary.
976 >     * then rethrows the exception, wrapping it in an AssertionError
977 >     * if necessary.
978       */
979      public void threadUnexpectedException(Throwable t) {
980          threadRecordFailure(t);
# Line 805 | Line 983 | public class JSR166TestCase extends Test
983              throw (RuntimeException) t;
984          else if (t instanceof Error)
985              throw (Error) t;
986 <        else {
987 <            AssertionFailedError afe =
810 <                new AssertionFailedError("unexpected exception: " + t);
811 <            afe.initCause(t);
812 <            throw afe;
813 <        }
986 >        else
987 >            throw new AssertionError("unexpected exception: " + t, t);
988      }
989  
990      /**
# Line 878 | Line 1052 | public class JSR166TestCase extends Test
1052          }};
1053      }
1054  
1055 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1056 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
1057 +    }
1058 +
1059 +    Runnable releaser(final AtomicBoolean flag) {
1060 +        return new Runnable() { public void run() { flag.set(true); }};
1061 +    }
1062 +
1063      /**
1064       * Waits out termination of a thread pool or fails doing so.
1065       */
1066      void joinPool(ExecutorService pool) {
1067          try {
1068              pool.shutdown();
1069 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1069 >            if (!pool.awaitTermination(20 * LONG_DELAY_MS, MILLISECONDS)) {
1070                  try {
1071                      threadFail("ExecutorService " + pool +
1072                                 " did not terminate in a timely manner");
# Line 901 | Line 1083 | public class JSR166TestCase extends Test
1083          }
1084      }
1085  
1086 <    /** Like Runnable, but with the freedom to throw anything */
1086 >    /**
1087 >     * Like Runnable, but with the freedom to throw anything.
1088 >     * junit folks had the same idea:
1089 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1090 >     */
1091      interface Action { public void run() throws Throwable; }
1092  
1093      /**
# Line 927 | Line 1113 | public class JSR166TestCase extends Test
1113          }
1114      }
1115  
1116 +    /** Returns true if thread info might be useful in a thread dump. */
1117 +    static boolean threadOfInterest(ThreadInfo info) {
1118 +        final String name = info.getThreadName();
1119 +        String lockName;
1120 +        if (name == null)
1121 +            return true;
1122 +        if (name.equals("Signal Dispatcher")
1123 +            || name.equals("WedgedTestDetector"))
1124 +            return false;
1125 +        if (name.equals("Reference Handler")) {
1126 +            // Reference Handler stacktrace changed in JDK-8156500
1127 +            StackTraceElement[] stackTrace; String methodName;
1128 +            if ((stackTrace = info.getStackTrace()) != null
1129 +                && stackTrace.length > 0
1130 +                && (methodName = stackTrace[0].getMethodName()) != null
1131 +                && methodName.equals("waitForReferencePendingList"))
1132 +                return false;
1133 +            // jdk8 Reference Handler stacktrace
1134 +            if ((lockName = info.getLockName()) != null
1135 +                && lockName.startsWith("java.lang.ref"))
1136 +                return false;
1137 +        }
1138 +        if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
1139 +            && (lockName = info.getLockName()) != null
1140 +            && lockName.startsWith("java.lang.ref"))
1141 +            return false;
1142 +        if (name.startsWith("ForkJoinPool.commonPool-worker")
1143 +            && (lockName = info.getLockName()) != null
1144 +            && lockName.startsWith("java.util.concurrent.ForkJoinPool"))
1145 +            return false;
1146 +        return true;
1147 +    }
1148 +
1149      /**
1150       * A debugging tool to print stack traces of most threads, as jstack does.
1151       * Uninteresting threads are filtered out.
1152       */
1153 +    @SuppressWarnings("removal")
1154      static void dumpTestThreads() {
1155 <        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1156 <        System.err.println("------ stacktrace dump start ------");
1157 <        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1158 <            String name = info.getThreadName();
1159 <            if ("Signal Dispatcher".equals(name))
1160 <                continue;
1161 <            if ("Reference Handler".equals(name)
942 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
943 <                continue;
944 <            if ("Finalizer".equals(name)
945 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
946 <                continue;
947 <            if ("checkForWedgedTest".equals(name))
948 <                continue;
949 <            System.err.print(info);
1155 >        SecurityManager sm = System.getSecurityManager();
1156 >        if (sm != null) {
1157 >            try {
1158 >                System.setSecurityManager(null);
1159 >            } catch (SecurityException giveUp) {
1160 >                return;
1161 >            }
1162          }
1163 +
1164 +        System.err.println("------ stacktrace dump start ------");
1165 +        for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true))
1166 +            if (threadOfInterest(info))
1167 +                System.err.print(info);
1168          System.err.println("------ stacktrace dump end ------");
952    }
1169  
1170 <    /**
955 <     * Checks that thread does not terminate within the default
956 <     * millisecond delay of {@code timeoutMillis()}.
957 <     */
958 <    void assertThreadStaysAlive(Thread thread) {
959 <        assertThreadStaysAlive(thread, timeoutMillis());
1170 >        if (sm != null) System.setSecurityManager(sm);
1171      }
1172  
1173      /**
1174 <     * Checks that thread does not terminate within the given millisecond delay.
1174 >     * Checks that thread eventually enters the expected blocked thread state.
1175       */
1176 <    void assertThreadStaysAlive(Thread thread, long millis) {
1177 <        try {
1178 <            // No need to optimize the failing case via Thread.join.
1179 <            delay(millis);
1180 <            assertTrue(thread.isAlive());
1181 <        } catch (InterruptedException fail) {
1182 <            threadFail("Unexpected InterruptedException");
1176 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1177 >        // always sleep at least 1 ms, with high probability avoiding
1178 >        // transitory states
1179 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1180 >            try { delay(1); }
1181 >            catch (InterruptedException fail) {
1182 >                throw new AssertionError("Unexpected InterruptedException", fail);
1183 >            }
1184 >            Thread.State s = thread.getState();
1185 >            if (s == expected)
1186 >                return;
1187 >            else if (s == Thread.State.TERMINATED)
1188 >                fail("Unexpected thread termination");
1189          }
1190 +        fail("timed out waiting for thread to enter thread state " + expected);
1191      }
1192  
1193      /**
1194 <     * Checks that the threads do not terminate within the default
977 <     * millisecond delay of {@code timeoutMillis()}.
1194 >     * Returns the thread's blocker's class name, if any, else null.
1195       */
1196 <    void assertThreadsStayAlive(Thread... threads) {
1197 <        assertThreadsStayAlive(timeoutMillis(), threads);
1198 <    }
1199 <
1200 <    /**
1201 <     * Checks that the threads do not terminate within the given millisecond delay.
985 <     */
986 <    void assertThreadsStayAlive(long millis, Thread... threads) {
987 <        try {
988 <            // No need to optimize the failing case via Thread.join.
989 <            delay(millis);
990 <            for (Thread thread : threads)
991 <                assertTrue(thread.isAlive());
992 <        } catch (InterruptedException fail) {
993 <            threadFail("Unexpected InterruptedException");
994 <        }
1196 >    String blockerClassName(Thread thread) {
1197 >        ThreadInfo threadInfo; LockInfo lockInfo;
1198 >        if ((threadInfo = THREAD_MXBEAN.getThreadInfo(thread.getId(), 0)) != null
1199 >            && (lockInfo = threadInfo.getLockInfo()) != null)
1200 >            return lockInfo.getClassName();
1201 >        return null;
1202      }
1203  
1204      /**
1205       * Checks that future.get times out, with the default timeout of
1206       * {@code timeoutMillis()}.
1207       */
1208 <    void assertFutureTimesOut(Future future) {
1208 >    void assertFutureTimesOut(Future<?> future) {
1209          assertFutureTimesOut(future, timeoutMillis());
1210      }
1211  
1212      /**
1213       * Checks that future.get times out, with the given millisecond timeout.
1214       */
1215 <    void assertFutureTimesOut(Future future, long timeoutMillis) {
1215 >    void assertFutureTimesOut(Future<?> future, long timeoutMillis) {
1216          long startTime = System.nanoTime();
1217          try {
1218              future.get(timeoutMillis, MILLISECONDS);
# Line 1013 | Line 1220 | public class JSR166TestCase extends Test
1220          } catch (TimeoutException success) {
1221          } catch (Exception fail) {
1222              threadUnexpectedException(fail);
1223 <        } finally { future.cancel(true); }
1223 >        }
1224          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1225 +        assertFalse(future.isDone());
1226      }
1227  
1228      /**
# Line 1032 | Line 1240 | public class JSR166TestCase extends Test
1240      }
1241  
1242      /**
1243 <     * The number of elements to place in collections, arrays, etc.
1243 >     * The maximum number of consecutive spurious wakeups we should
1244 >     * tolerate (from APIs like LockSupport.park) before failing a test.
1245       */
1246 <    public static final int SIZE = 20;
1246 >    static final int MAX_SPURIOUS_WAKEUPS = 10;
1247  
1248 <    // Some convenient Integer constants
1248 >    /**
1249 >     * The number of elements to place in collections, arrays, etc.
1250 >     * Must be at least ten;
1251 >     */
1252 >    public static final int SIZE = 32;
1253  
1254 <    public static final Integer zero  = new Integer(0);
1255 <    public static final Integer one   = new Integer(1);
1256 <    public static final Integer two   = new Integer(2);
1257 <    public static final Integer three = new Integer(3);
1258 <    public static final Integer four  = new Integer(4);
1259 <    public static final Integer five  = new Integer(5);
1260 <    public static final Integer six   = new Integer(6);
1261 <    public static final Integer seven = new Integer(7);
1262 <    public static final Integer eight = new Integer(8);
1263 <    public static final Integer nine  = new Integer(9);
1264 <    public static final Integer m1  = new Integer(-1);
1265 <    public static final Integer m2  = new Integer(-2);
1266 <    public static final Integer m3  = new Integer(-3);
1267 <    public static final Integer m4  = new Integer(-4);
1268 <    public static final Integer m5  = new Integer(-5);
1269 <    public static final Integer m6  = new Integer(-6);
1270 <    public static final Integer m10 = new Integer(-10);
1254 >    static Item[] seqItems(int size) {
1255 >        Item[] s = new Item[size];
1256 >        for (int i = 0; i < size; ++i)
1257 >            s[i] = new Item(i);
1258 >        return s;
1259 >    }
1260 >    static Item[] negativeSeqItems(int size) {
1261 >        Item[] s = new Item[size];
1262 >        for (int i = 0; i < size; ++i)
1263 >            s[i] = new Item(-i);
1264 >        return s;
1265 >    }
1266 >
1267 >    // Many tests rely on defaultItems all being sequential nonnegative
1268 >    public static final Item[] defaultItems = seqItems(SIZE);
1269 >
1270 >    static Item itemFor(int i) { // check cache for defaultItems
1271 >        Item[] items = defaultItems;
1272 >        return (i >= 0 && i < items.length) ? items[i] : new Item(i);
1273 >    }
1274 >
1275 >    public static final Item zero  = defaultItems[0];
1276 >    public static final Item one   = defaultItems[1];
1277 >    public static final Item two   = defaultItems[2];
1278 >    public static final Item three = defaultItems[3];
1279 >    public static final Item four  = defaultItems[4];
1280 >    public static final Item five  = defaultItems[5];
1281 >    public static final Item six   = defaultItems[6];
1282 >    public static final Item seven = defaultItems[7];
1283 >    public static final Item eight = defaultItems[8];
1284 >    public static final Item nine  = defaultItems[9];
1285 >    public static final Item ten   = defaultItems[10];
1286 >
1287 >    public static final Item[] negativeItems = negativeSeqItems(SIZE);
1288 >
1289 >    public static final Item minusOne   = negativeItems[1];
1290 >    public static final Item minusTwo   = negativeItems[2];
1291 >    public static final Item minusThree = negativeItems[3];
1292 >    public static final Item minusFour  = negativeItems[4];
1293 >    public static final Item minusFive  = negativeItems[5];
1294 >    public static final Item minusSix   = negativeItems[6];
1295 >    public static final Item minusSeven = negativeItems[7];
1296 >    public static final Item minusEight = negativeItems[8];
1297 >    public static final Item minusNone  = negativeItems[9];
1298 >    public static final Item minusTen   = negativeItems[10];
1299 >
1300 >    // elements expected to be missing
1301 >    public static final Item fortytwo = new Item(42);
1302 >    public static final Item eightysix = new Item(86);
1303 >    public static final Item ninetynine = new Item(99);
1304 >
1305 >    // Interop across Item, int
1306 >
1307 >    static void mustEqual(Item x, Item y) {
1308 >        if (x != y)
1309 >            assertEquals(x.value, y.value);
1310 >    }
1311 >    static void mustEqual(Item x, int y) {
1312 >        assertEquals(x.value, y);
1313 >    }
1314 >    static void mustEqual(int x, Item y) {
1315 >        assertEquals(x, y.value);
1316 >    }
1317 >    static void mustEqual(int x, int y) {
1318 >        assertEquals(x, y);
1319 >    }
1320 >    static void mustEqual(Object x, Object y) {
1321 >        if (x != y)
1322 >            assertEquals(x, y);
1323 >    }
1324 >    static void mustEqual(int x, Object y) {
1325 >        if (y instanceof Item)
1326 >            assertEquals(x, ((Item)y).value);
1327 >        else fail();
1328 >    }
1329 >    static void mustEqual(Object x, int y) {
1330 >        if (x instanceof Item)
1331 >            assertEquals(((Item)x).value, y);
1332 >        else fail();
1333 >    }
1334 >    static void mustEqual(boolean x, boolean y) {
1335 >        assertEquals(x, y);
1336 >    }
1337 >    static void mustEqual(long x, long y) {
1338 >        assertEquals(x, y);
1339 >    }
1340 >    static void mustEqual(double x, double y) {
1341 >        assertEquals(x, y);
1342 >    }
1343 >    static void mustContain(Collection<Item> c, int i) {
1344 >        assertTrue(c.contains(itemFor(i)));
1345 >    }
1346 >    static void mustContain(Collection<Item> c, Item i) {
1347 >        assertTrue(c.contains(i));
1348 >    }
1349 >    static void mustNotContain(Collection<Item> c, int i) {
1350 >        assertFalse(c.contains(itemFor(i)));
1351 >    }
1352 >    static void mustNotContain(Collection<Item> c, Item i) {
1353 >        assertFalse(c.contains(i));
1354 >    }
1355 >    static void mustRemove(Collection<Item> c, int i) {
1356 >        assertTrue(c.remove(itemFor(i)));
1357 >    }
1358 >    static void mustRemove(Collection<Item> c, Item i) {
1359 >        assertTrue(c.remove(i));
1360 >    }
1361 >    static void mustNotRemove(Collection<Item> c, int i) {
1362 >        assertFalse(c.remove(itemFor(i)));
1363 >    }
1364 >    static void mustNotRemove(Collection<Item> c, Item i) {
1365 >        assertFalse(c.remove(i));
1366 >    }
1367 >    static void mustAdd(Collection<Item> c, int i) {
1368 >        assertTrue(c.add(itemFor(i)));
1369 >    }
1370 >    static void mustAdd(Collection<Item> c, Item i) {
1371 >        assertTrue(c.add(i));
1372 >    }
1373 >    static void mustOffer(Queue<Item> c, int i) {
1374 >        assertTrue(c.offer(itemFor(i)));
1375 >    }
1376 >    static void mustOffer(Queue<Item> c, Item i) {
1377 >        assertTrue(c.offer(i));
1378 >    }
1379  
1380      /**
1381       * Runs Runnable r with a security policy that permits precisely
# Line 1063 | Line 1384 | public class JSR166TestCase extends Test
1384       * security manager.  We require that any security manager permit
1385       * getPolicy/setPolicy.
1386       */
1387 +    @SuppressWarnings("removal")
1388      public void runWithPermissions(Runnable r, Permission... permissions) {
1389          SecurityManager sm = System.getSecurityManager();
1390          if (sm == null) {
# Line 1078 | Line 1400 | public class JSR166TestCase extends Test
1400       * Runnable.  We require that any security manager permit
1401       * getPolicy/setPolicy.
1402       */
1403 +    @SuppressWarnings("removal")
1404      public void runWithSecurityManagerWithPermissions(Runnable r,
1405                                                        Permission... permissions) {
1406 +        if (!useSecurityManager) return;
1407          SecurityManager sm = System.getSecurityManager();
1408          if (sm == null) {
1409              Policy savedPolicy = Policy.getPolicy();
# Line 1116 | Line 1440 | public class JSR166TestCase extends Test
1440       * A security policy where new permissions can be dynamically added
1441       * or all cleared.
1442       */
1443 +    @SuppressWarnings("removal")
1444      public static class AdjustablePolicy extends java.security.Policy {
1445          Permissions perms = new Permissions();
1446          AdjustablePolicy(Permission... permissions) {
# Line 1135 | Line 1460 | public class JSR166TestCase extends Test
1460          }
1461          public void refresh() {}
1462          public String toString() {
1463 <            List<Permission> ps = new ArrayList<Permission>();
1463 >            List<Permission> ps = new ArrayList<>();
1464              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1465                  ps.add(e.nextElement());
1466              return "AdjustablePolicy with permissions " + ps;
# Line 1145 | Line 1470 | public class JSR166TestCase extends Test
1470      /**
1471       * Returns a policy containing all the permissions we ever need.
1472       */
1473 +    @SuppressWarnings("removal")
1474      public static Policy permissivePolicy() {
1475          return new AdjustablePolicy
1476              // Permissions j.u.c. needs directly
# Line 1163 | Line 1489 | public class JSR166TestCase extends Test
1489  
1490      /**
1491       * Sleeps until the given time has elapsed.
1492 <     * Throws AssertionFailedError if interrupted.
1492 >     * Throws AssertionError if interrupted.
1493       */
1494 <    void sleep(long millis) {
1494 >    static void sleep(long millis) {
1495          try {
1496              delay(millis);
1497          } catch (InterruptedException fail) {
1498 <            AssertionFailedError afe =
1173 <                new AssertionFailedError("Unexpected InterruptedException");
1174 <            afe.initCause(fail);
1175 <            throw afe;
1498 >            throw new AssertionError("Unexpected InterruptedException", fail);
1499          }
1500      }
1501  
1502      /**
1503       * Spin-waits up to the specified number of milliseconds for the given
1504       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1505 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1506       */
1507 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1508 <        long startTime = System.nanoTime();
1509 <        for (;;) {
1510 <            Thread.State s = thread.getState();
1511 <            if (s == Thread.State.BLOCKED ||
1512 <                s == Thread.State.WAITING ||
1513 <                s == Thread.State.TIMED_WAITING)
1514 <                return;
1515 <            else if (s == Thread.State.TERMINATED)
1507 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1508 >                                       Callable<Boolean> waitingForGodot) {
1509 >        for (long startTime = 0L;;) {
1510 >            switch (thread.getState()) {
1511 >            default: break;
1512 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1513 >                try {
1514 >                    if (waitingForGodot == null || waitingForGodot.call())
1515 >                        return;
1516 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1517 >                break;
1518 >            case TERMINATED:
1519                  fail("Unexpected thread termination");
1520 +            }
1521 +
1522 +            if (startTime == 0L)
1523 +                startTime = System.nanoTime();
1524              else if (millisElapsedSince(startTime) > timeoutMillis) {
1525 <                threadAssertTrue(thread.isAlive());
1526 <                return;
1525 >                assertTrue(thread.isAlive());
1526 >                if (waitingForGodot == null
1527 >                    || thread.getState() == Thread.State.RUNNABLE)
1528 >                    fail("timed out waiting for thread to enter wait state");
1529 >                else
1530 >                    fail("timed out waiting for condition, thread state="
1531 >                         + thread.getState());
1532              }
1533              Thread.yield();
1534          }
1535      }
1536  
1537      /**
1538 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1539 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1538 >     * Spin-waits up to the specified number of milliseconds for the given
1539 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1540 >     */
1541 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1542 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1543 >    }
1544 >
1545 >    /**
1546 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1547 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1548       */
1549      void waitForThreadToEnterWaitState(Thread thread) {
1550 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1550 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1551 >    }
1552 >
1553 >    /**
1554 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1555 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1556 >     * and additionally satisfy the given condition.
1557 >     */
1558 >    void waitForThreadToEnterWaitState(Thread thread,
1559 >                                       Callable<Boolean> waitingForGodot) {
1560 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1561 >    }
1562 >
1563 >    /**
1564 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1565 >     * be interrupted.  Clears the interrupt status before returning.
1566 >     */
1567 >    void awaitInterrupted() {
1568 >        for (long startTime = 0L; !Thread.interrupted(); ) {
1569 >            if (startTime == 0L)
1570 >                startTime = System.nanoTime();
1571 >            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1572 >                fail("timed out waiting for thread interrupt");
1573 >            Thread.yield();
1574 >        }
1575      }
1576  
1577      /**
# Line 1215 | Line 1583 | public class JSR166TestCase extends Test
1583          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1584      }
1585  
1218 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1219 //         long startTime = System.nanoTime();
1220 //         try {
1221 //             r.run();
1222 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1223 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1224 //             throw new AssertionFailedError("did not return promptly");
1225 //     }
1226
1227 //     void assertTerminatesPromptly(Runnable r) {
1228 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1229 //     }
1230
1586      /**
1587       * Checks that timed f.get() returns the expected value, and does not
1588       * wait for the timeout to elapse before returning.
1589       */
1590      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1591          long startTime = System.nanoTime();
1592 +        T actual = null;
1593          try {
1594 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1594 >            actual = f.get(timeoutMillis, MILLISECONDS);
1595          } catch (Throwable fail) { threadUnexpectedException(fail); }
1596 +        assertEquals(expectedValue, actual);
1597          if (millisElapsedSince(startTime) > timeoutMillis/2)
1598 <            throw new AssertionFailedError("timed get did not return promptly");
1598 >            throw new AssertionError("timed get did not return promptly");
1599      }
1600  
1601      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1256 | Line 1613 | public class JSR166TestCase extends Test
1613      }
1614  
1615      /**
1616 +     * Returns a new started daemon Thread running the given action,
1617 +     * wrapped in a CheckedRunnable.
1618 +     */
1619 +    Thread newStartedThread(Action action) {
1620 +        return newStartedThread(checkedRunnable(action));
1621 +    }
1622 +
1623 +    /**
1624       * Waits for the specified time (in milliseconds) for the thread
1625       * to terminate (using {@link Thread#join(long)}), else interrupts
1626       * the thread (in the hope that it may terminate later) and fails.
1627       */
1628 <    void awaitTermination(Thread t, long timeoutMillis) {
1628 >    void awaitTermination(Thread thread, long timeoutMillis) {
1629          try {
1630 <            t.join(timeoutMillis);
1630 >            thread.join(timeoutMillis);
1631          } catch (InterruptedException fail) {
1632              threadUnexpectedException(fail);
1633 <        } finally {
1634 <            if (t.getState() != Thread.State.TERMINATED) {
1635 <                t.interrupt();
1636 <                threadFail("timed out waiting for thread to terminate");
1633 >        }
1634 >        if (thread.getState() != Thread.State.TERMINATED) {
1635 >            String detail = String.format(
1636 >                    "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1637 >                    thread, thread.getState());
1638 >            try {
1639 >                threadFail(detail);
1640 >            } finally {
1641 >                // Interrupt thread __after__ having reported its stack trace
1642 >                thread.interrupt();
1643              }
1644          }
1645      }
# Line 1296 | Line 1667 | public class JSR166TestCase extends Test
1667          }
1668      }
1669  
1670 <    public abstract class RunnableShouldThrow implements Runnable {
1671 <        protected abstract void realRun() throws Throwable;
1672 <
1673 <        final Class<?> exceptionClass;
1674 <
1304 <        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1305 <            this.exceptionClass = exceptionClass;
1306 <        }
1307 <
1308 <        public final void run() {
1309 <            try {
1310 <                realRun();
1311 <                threadShouldThrow(exceptionClass.getSimpleName());
1312 <            } catch (Throwable t) {
1313 <                if (! exceptionClass.isInstance(t))
1314 <                    threadUnexpectedException(t);
1315 <            }
1316 <        }
1670 >    Runnable checkedRunnable(Action action) {
1671 >        return new CheckedRunnable() {
1672 >            public void realRun() throws Throwable {
1673 >                action.run();
1674 >            }};
1675      }
1676  
1677      public abstract class ThreadShouldThrow extends Thread {
# Line 1328 | Line 1686 | public class JSR166TestCase extends Test
1686          public final void run() {
1687              try {
1688                  realRun();
1331                threadShouldThrow(exceptionClass.getSimpleName());
1689              } catch (Throwable t) {
1690                  if (! exceptionClass.isInstance(t))
1691                      threadUnexpectedException(t);
1692 +                return;
1693              }
1694 +            threadShouldThrow(exceptionClass.getSimpleName());
1695          }
1696      }
1697  
# Line 1342 | Line 1701 | public class JSR166TestCase extends Test
1701          public final void run() {
1702              try {
1703                  realRun();
1345                threadShouldThrow("InterruptedException");
1704              } catch (InterruptedException success) {
1705                  threadAssertFalse(Thread.interrupted());
1706 +                return;
1707              } catch (Throwable fail) {
1708                  threadUnexpectedException(fail);
1709              }
1710 +            threadShouldThrow("InterruptedException");
1711          }
1712      }
1713  
# Line 1359 | Line 1719 | public class JSR166TestCase extends Test
1719                  return realCall();
1720              } catch (Throwable fail) {
1721                  threadUnexpectedException(fail);
1362                return null;
1363            }
1364        }
1365    }
1366
1367    public abstract class CheckedInterruptedCallable<T>
1368        implements Callable<T> {
1369        protected abstract T realCall() throws Throwable;
1370
1371        public final T call() {
1372            try {
1373                T result = realCall();
1374                threadShouldThrow("InterruptedException");
1375                return result;
1376            } catch (InterruptedException success) {
1377                threadAssertFalse(Thread.interrupted());
1378            } catch (Throwable fail) {
1379                threadUnexpectedException(fail);
1722              }
1723 <            return null;
1723 >            throw new AssertionError("unreached");
1724          }
1725      }
1726  
# Line 1386 | Line 1728 | public class JSR166TestCase extends Test
1728          public void run() {}
1729      }
1730  
1731 <    public static class NoOpCallable implements Callable {
1731 >    public static class NoOpCallable implements Callable<Object> {
1732          public Object call() { return Boolean.TRUE; }
1733      }
1734  
# Line 1434 | Line 1776 | public class JSR166TestCase extends Test
1776          return new LatchAwaiter(latch);
1777      }
1778  
1779 <    public void await(CountDownLatch latch) {
1779 >    public void await(CountDownLatch latch, long timeoutMillis) {
1780 >        boolean timedOut = false;
1781          try {
1782 <            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1440 <                fail("timed out waiting for CountDownLatch for "
1441 <                     + (LONG_DELAY_MS/1000) + " sec");
1782 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1783          } catch (Throwable fail) {
1784              threadUnexpectedException(fail);
1785          }
1786 +        if (timedOut)
1787 +            fail("timed out waiting for CountDownLatch for "
1788 +                 + (timeoutMillis/1000) + " sec");
1789 +    }
1790 +
1791 +    public void await(CountDownLatch latch) {
1792 +        await(latch, LONG_DELAY_MS);
1793      }
1794  
1795      public void await(Semaphore semaphore) {
1796 +        boolean timedOut = false;
1797          try {
1798 <            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1799 <                fail("timed out waiting for Semaphore for "
1800 <                     + (LONG_DELAY_MS/1000) + " sec");
1798 >            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1799 >        } catch (Throwable fail) {
1800 >            threadUnexpectedException(fail);
1801 >        }
1802 >        if (timedOut)
1803 >            fail("timed out waiting for Semaphore for "
1804 >                 + (LONG_DELAY_MS/1000) + " sec");
1805 >    }
1806 >
1807 >    public void await(CyclicBarrier barrier) {
1808 >        try {
1809 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1810          } catch (Throwable fail) {
1811              threadUnexpectedException(fail);
1812          }
# Line 1468 | Line 1826 | public class JSR166TestCase extends Test
1826   //         long startTime = System.nanoTime();
1827   //         while (!flag.get()) {
1828   //             if (millisElapsedSince(startTime) > timeoutMillis)
1829 < //                 throw new AssertionFailedError("timed out");
1829 > //                 throw new AssertionError("timed out");
1830   //             Thread.yield();
1831   //         }
1832   //     }
# Line 1477 | Line 1835 | public class JSR166TestCase extends Test
1835          public String call() { throw new NullPointerException(); }
1836      }
1837  
1480    public static class CallableOne implements Callable<Integer> {
1481        public Integer call() { return one; }
1482    }
1483
1484    public class ShortRunnable extends CheckedRunnable {
1485        protected void realRun() throws Throwable {
1486            delay(SHORT_DELAY_MS);
1487        }
1488    }
1489
1490    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1491        protected void realRun() throws InterruptedException {
1492            delay(SHORT_DELAY_MS);
1493        }
1494    }
1495
1496    public class SmallRunnable extends CheckedRunnable {
1497        protected void realRun() throws Throwable {
1498            delay(SMALL_DELAY_MS);
1499        }
1500    }
1501
1502    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1503        protected void realRun() {
1504            try {
1505                delay(SMALL_DELAY_MS);
1506            } catch (InterruptedException ok) {}
1507        }
1508    }
1509
1510    public class SmallCallable extends CheckedCallable {
1511        protected Object realCall() throws InterruptedException {
1512            delay(SMALL_DELAY_MS);
1513            return Boolean.TRUE;
1514        }
1515    }
1516
1517    public class MediumRunnable extends CheckedRunnable {
1518        protected void realRun() throws Throwable {
1519            delay(MEDIUM_DELAY_MS);
1520        }
1521    }
1522
1523    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1524        protected void realRun() throws InterruptedException {
1525            delay(MEDIUM_DELAY_MS);
1526        }
1527    }
1528
1838      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1839          return new CheckedRunnable() {
1840              protected void realRun() {
# Line 1535 | Line 1844 | public class JSR166TestCase extends Test
1844              }};
1845      }
1846  
1538    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1539        protected void realRun() {
1540            try {
1541                delay(MEDIUM_DELAY_MS);
1542            } catch (InterruptedException ok) {}
1543        }
1544    }
1545
1546    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1547        protected void realRun() {
1548            try {
1549                delay(LONG_DELAY_MS);
1550            } catch (InterruptedException ok) {}
1551        }
1552    }
1553
1847      /**
1848       * For use as ThreadFactory in constructors
1849       */
# Line 1564 | Line 1857 | public class JSR166TestCase extends Test
1857          boolean isDone();
1858      }
1859  
1567    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1568        return new TrackedRunnable() {
1569                private volatile boolean done = false;
1570                public boolean isDone() { return done; }
1571                public void run() {
1572                    try {
1573                        delay(timeoutMillis);
1574                        done = true;
1575                    } catch (InterruptedException ok) {}
1576                }
1577            };
1578    }
1579
1580    public static class TrackedShortRunnable implements Runnable {
1581        public volatile boolean done = false;
1582        public void run() {
1583            try {
1584                delay(SHORT_DELAY_MS);
1585                done = true;
1586            } catch (InterruptedException ok) {}
1587        }
1588    }
1589
1590    public static class TrackedSmallRunnable implements Runnable {
1591        public volatile boolean done = false;
1592        public void run() {
1593            try {
1594                delay(SMALL_DELAY_MS);
1595                done = true;
1596            } catch (InterruptedException ok) {}
1597        }
1598    }
1599
1600    public static class TrackedMediumRunnable implements Runnable {
1601        public volatile boolean done = false;
1602        public void run() {
1603            try {
1604                delay(MEDIUM_DELAY_MS);
1605                done = true;
1606            } catch (InterruptedException ok) {}
1607        }
1608    }
1609
1610    public static class TrackedLongRunnable implements Runnable {
1611        public volatile boolean done = false;
1612        public void run() {
1613            try {
1614                delay(LONG_DELAY_MS);
1615                done = true;
1616            } catch (InterruptedException ok) {}
1617        }
1618    }
1619
1860      public static class TrackedNoOpRunnable implements Runnable {
1861          public volatile boolean done = false;
1862          public void run() {
# Line 1624 | Line 1864 | public class JSR166TestCase extends Test
1864          }
1865      }
1866  
1627    public static class TrackedCallable implements Callable {
1628        public volatile boolean done = false;
1629        public Object call() {
1630            try {
1631                delay(SMALL_DELAY_MS);
1632                done = true;
1633            } catch (InterruptedException ok) {}
1634            return Boolean.TRUE;
1635        }
1636    }
1637
1867      /**
1868       * Analog of CheckedRunnable for RecursiveAction
1869       */
# Line 1661 | Line 1890 | public class JSR166TestCase extends Test
1890                  return realCompute();
1891              } catch (Throwable fail) {
1892                  threadUnexpectedException(fail);
1664                return null;
1893              }
1894 +            throw new AssertionError("unreached");
1895          }
1896      }
1897  
# Line 1676 | Line 1905 | public class JSR166TestCase extends Test
1905  
1906      /**
1907       * A CyclicBarrier that uses timed await and fails with
1908 <     * AssertionFailedErrors instead of throwing checked exceptions.
1908 >     * AssertionErrors instead of throwing checked exceptions.
1909       */
1910 <    public class CheckedBarrier extends CyclicBarrier {
1910 >    public static class CheckedBarrier extends CyclicBarrier {
1911          public CheckedBarrier(int parties) { super(parties); }
1912  
1913          public int await() {
1914              try {
1915 <                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1915 >                return super.await(LONGER_DELAY_MS, MILLISECONDS);
1916              } catch (TimeoutException timedOut) {
1917 <                throw new AssertionFailedError("timed out");
1917 >                throw new AssertionError("timed out");
1918              } catch (Exception fail) {
1919 <                AssertionFailedError afe =
1691 <                    new AssertionFailedError("Unexpected exception: " + fail);
1692 <                afe.initCause(fail);
1693 <                throw afe;
1919 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1920              }
1921          }
1922      }
1923  
1924 <    void checkEmpty(BlockingQueue q) {
1924 >    void checkEmpty(BlockingQueue<?> q) {
1925          try {
1926              assertTrue(q.isEmpty());
1927              assertEquals(0, q.size());
1928              assertNull(q.peek());
1929              assertNull(q.poll());
1930 <            assertNull(q.poll(0, MILLISECONDS));
1930 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1931              assertEquals(q.toString(), "[]");
1932              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1933              assertFalse(q.iterator().hasNext());
# Line 1743 | Line 1969 | public class JSR166TestCase extends Test
1969      }
1970  
1971      @SuppressWarnings("unchecked")
1972 +    void assertImmutable(Object o) {
1973 +        if (o instanceof Collection) {
1974 +            assertThrows(
1975 +                UnsupportedOperationException.class,
1976 +                () -> ((Collection) o).add(null));
1977 +        }
1978 +    }
1979 +
1980 +    @SuppressWarnings("unchecked")
1981      <T> T serialClone(T o) {
1982 +        T clone = null;
1983          try {
1984              ObjectInputStream ois = new ObjectInputStream
1985                  (new ByteArrayInputStream(serialBytes(o)));
1986 <            T clone = (T) ois.readObject();
1751 <            assertSame(o.getClass(), clone.getClass());
1752 <            return clone;
1986 >            clone = (T) ois.readObject();
1987          } catch (Throwable fail) {
1988              threadUnexpectedException(fail);
1989 +        }
1990 +        if (o == clone) assertImmutable(o);
1991 +        else assertSame(o.getClass(), clone.getClass());
1992 +        return clone;
1993 +    }
1994 +
1995 +    /**
1996 +     * A version of serialClone that leaves error handling (for
1997 +     * e.g. NotSerializableException) up to the caller.
1998 +     */
1999 +    @SuppressWarnings("unchecked")
2000 +    <T> T serialClonePossiblyFailing(T o)
2001 +        throws ReflectiveOperationException, java.io.IOException {
2002 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
2003 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
2004 +        oos.writeObject(o);
2005 +        oos.flush();
2006 +        oos.close();
2007 +        ObjectInputStream ois = new ObjectInputStream
2008 +            (new ByteArrayInputStream(bos.toByteArray()));
2009 +        T clone = (T) ois.readObject();
2010 +        if (o == clone) assertImmutable(o);
2011 +        else assertSame(o.getClass(), clone.getClass());
2012 +        return clone;
2013 +    }
2014 +
2015 +    /**
2016 +     * If o implements Cloneable and has a public clone method,
2017 +     * returns a clone of o, else null.
2018 +     */
2019 +    @SuppressWarnings("unchecked")
2020 +    <T> T cloneableClone(T o) {
2021 +        if (!(o instanceof Cloneable)) return null;
2022 +        final T clone;
2023 +        try {
2024 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
2025 +        } catch (NoSuchMethodException ok) {
2026              return null;
2027 +        } catch (ReflectiveOperationException unexpected) {
2028 +            throw new Error(unexpected);
2029          }
2030 +        assertNotSame(o, clone); // not 100% guaranteed by spec
2031 +        assertSame(o.getClass(), clone.getClass());
2032 +        return clone;
2033      }
2034  
2035      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
2036 <                             Runnable... throwingActions) {
2037 <        for (Runnable throwingAction : throwingActions) {
2036 >                             Action... throwingActions) {
2037 >        for (Action throwingAction : throwingActions) {
2038              boolean threw = false;
2039              try { throwingAction.run(); }
2040              catch (Throwable t) {
2041                  threw = true;
2042 <                if (!expectedExceptionClass.isInstance(t)) {
2043 <                    AssertionFailedError afe =
2044 <                        new AssertionFailedError
2045 <                        ("Expected " + expectedExceptionClass.getName() +
2046 <                         ", got " + t.getClass().getName());
1771 <                    afe.initCause(t);
1772 <                    threadUnexpectedException(afe);
1773 <                }
2042 >                if (!expectedExceptionClass.isInstance(t))
2043 >                    throw new AssertionError(
2044 >                            "Expected " + expectedExceptionClass.getName() +
2045 >                            ", got " + t.getClass().getName(),
2046 >                            t);
2047              }
2048              if (!threw)
2049                  shouldThrow(expectedExceptionClass.getName());
# Line 1784 | Line 2057 | public class JSR166TestCase extends Test
2057          } catch (NoSuchElementException success) {}
2058          assertFalse(it.hasNext());
2059      }
2060 +
2061 +    public <T> Callable<T> callableThrowing(final Exception ex) {
2062 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
2063 +    }
2064 +
2065 +    public Runnable runnableThrowing(final RuntimeException ex) {
2066 +        return new Runnable() { public void run() { throw ex; }};
2067 +    }
2068 +
2069 +    /** A reusable thread pool to be shared by tests. */
2070 +    static final ExecutorService cachedThreadPool =
2071 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
2072 +                               1000L, MILLISECONDS,
2073 +                               new SynchronousQueue<Runnable>());
2074 +
2075 +    static <T> void shuffle(T[] array) {
2076 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
2077 +    }
2078 +
2079 +    /**
2080 +     * Returns the same String as would be returned by {@link
2081 +     * Object#toString}, whether or not the given object's class
2082 +     * overrides toString().
2083 +     *
2084 +     * @see System#identityHashCode
2085 +     */
2086 +    static String identityString(Object x) {
2087 +        return x.getClass().getName()
2088 +            + "@" + Integer.toHexString(System.identityHashCode(x));
2089 +    }
2090 +
2091 +    // --- Shared assertions for Executor tests ---
2092 +
2093 +    /**
2094 +     * Returns maximum number of tasks that can be submitted to given
2095 +     * pool (with bounded queue) before saturation (when submission
2096 +     * throws RejectedExecutionException).
2097 +     */
2098 +    static final int saturatedSize(ThreadPoolExecutor pool) {
2099 +        BlockingQueue<Runnable> q = pool.getQueue();
2100 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
2101 +    }
2102 +
2103 +    @SuppressWarnings("FutureReturnValueIgnored")
2104 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
2105 +        try {
2106 +            e.execute((Runnable) null);
2107 +            shouldThrow();
2108 +        } catch (NullPointerException success) {}
2109 +
2110 +        if (! (e instanceof ExecutorService)) return;
2111 +        ExecutorService es = (ExecutorService) e;
2112 +        try {
2113 +            es.submit((Runnable) null);
2114 +            shouldThrow();
2115 +        } catch (NullPointerException success) {}
2116 +        try {
2117 +            es.submit((Runnable) null, Boolean.TRUE);
2118 +            shouldThrow();
2119 +        } catch (NullPointerException success) {}
2120 +        try {
2121 +            es.submit((Callable<?>) null);
2122 +            shouldThrow();
2123 +        } catch (NullPointerException success) {}
2124 +
2125 +        if (! (e instanceof ScheduledExecutorService)) return;
2126 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
2127 +        try {
2128 +            ses.schedule((Runnable) null,
2129 +                         randomTimeout(), randomTimeUnit());
2130 +            shouldThrow();
2131 +        } catch (NullPointerException success) {}
2132 +        try {
2133 +            ses.schedule((Callable<?>) null,
2134 +                         randomTimeout(), randomTimeUnit());
2135 +            shouldThrow();
2136 +        } catch (NullPointerException success) {}
2137 +        try {
2138 +            ses.scheduleAtFixedRate((Runnable) null,
2139 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2140 +            shouldThrow();
2141 +        } catch (NullPointerException success) {}
2142 +        try {
2143 +            ses.scheduleWithFixedDelay((Runnable) null,
2144 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2145 +            shouldThrow();
2146 +        } catch (NullPointerException success) {}
2147 +    }
2148 +
2149 +    void setRejectedExecutionHandler(
2150 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2151 +        p.setRejectedExecutionHandler(handler);
2152 +        assertSame(handler, p.getRejectedExecutionHandler());
2153 +    }
2154 +
2155 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2156 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2157 +        final long savedTaskCount = p.getTaskCount();
2158 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2159 +        final int savedQueueSize = p.getQueue().size();
2160 +        final boolean stock = (p.getClass().getClassLoader() == null);
2161 +
2162 +        Runnable r = () -> {};
2163 +        Callable<Boolean> c = () -> Boolean.TRUE;
2164 +
2165 +        class Recorder implements RejectedExecutionHandler {
2166 +            public volatile Runnable r = null;
2167 +            public volatile ThreadPoolExecutor p = null;
2168 +            public void reset() { r = null; p = null; }
2169 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2170 +                assertNull(this.r);
2171 +                assertNull(this.p);
2172 +                this.r = r;
2173 +                this.p = p;
2174 +            }
2175 +        }
2176 +
2177 +        // check custom handler is invoked exactly once per task
2178 +        Recorder recorder = new Recorder();
2179 +        setRejectedExecutionHandler(p, recorder);
2180 +        for (int i = 2; i--> 0; ) {
2181 +            recorder.reset();
2182 +            p.execute(r);
2183 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2184 +                assertSame(r, recorder.r);
2185 +            assertSame(p, recorder.p);
2186 +
2187 +            recorder.reset();
2188 +            assertFalse(p.submit(r).isDone());
2189 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2190 +            assertSame(p, recorder.p);
2191 +
2192 +            recorder.reset();
2193 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2194 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2195 +            assertSame(p, recorder.p);
2196 +
2197 +            recorder.reset();
2198 +            assertFalse(p.submit(c).isDone());
2199 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2200 +            assertSame(p, recorder.p);
2201 +
2202 +            if (p instanceof ScheduledExecutorService) {
2203 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2204 +                ScheduledFuture<?> future;
2205 +
2206 +                recorder.reset();
2207 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2208 +                assertFalse(future.isDone());
2209 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2210 +                assertSame(p, recorder.p);
2211 +
2212 +                recorder.reset();
2213 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2214 +                assertFalse(future.isDone());
2215 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2216 +                assertSame(p, recorder.p);
2217 +
2218 +                recorder.reset();
2219 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2220 +                assertFalse(future.isDone());
2221 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2222 +                assertSame(p, recorder.p);
2223 +
2224 +                recorder.reset();
2225 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2226 +                assertFalse(future.isDone());
2227 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2228 +                assertSame(p, recorder.p);
2229 +            }
2230 +        }
2231 +
2232 +        // Checking our custom handler above should be sufficient, but
2233 +        // we add some integration tests of standard handlers.
2234 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2235 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2236 +
2237 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2238 +        try {
2239 +            p.execute(setThread);
2240 +            shouldThrow();
2241 +        } catch (RejectedExecutionException success) {}
2242 +        assertNull(thread.get());
2243 +
2244 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2245 +        p.execute(setThread);
2246 +        assertNull(thread.get());
2247 +
2248 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2249 +        p.execute(setThread);
2250 +        if (p.isShutdown())
2251 +            assertNull(thread.get());
2252 +        else
2253 +            assertSame(Thread.currentThread(), thread.get());
2254 +
2255 +        setRejectedExecutionHandler(p, savedHandler);
2256 +
2257 +        // check that pool was not perturbed by handlers
2258 +        assertEquals(savedTaskCount, p.getTaskCount());
2259 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2260 +        assertEquals(savedQueueSize, p.getQueue().size());
2261 +    }
2262 +
2263 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2264 +        assertEquals(x, y);
2265 +        assertEquals(y, x);
2266 +        assertEquals(x.isEmpty(), y.isEmpty());
2267 +        assertEquals(x.size(), y.size());
2268 +        if (x instanceof List) {
2269 +            assertEquals(x.toString(), y.toString());
2270 +        }
2271 +        if (x instanceof List || x instanceof Set) {
2272 +            assertEquals(x.hashCode(), y.hashCode());
2273 +        }
2274 +        if (x instanceof List || x instanceof Deque) {
2275 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2276 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2277 +                                     y.toArray(new Object[0])));
2278 +        }
2279 +    }
2280 +
2281 +    /**
2282 +     * A weaker form of assertCollectionsEquals which does not insist
2283 +     * that the two collections satisfy Object#equals(Object), since
2284 +     * they may use identity semantics as Deques do.
2285 +     */
2286 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2287 +        if (x instanceof List || x instanceof Set)
2288 +            assertCollectionsEquals(x, y);
2289 +        else {
2290 +            assertEquals(x.isEmpty(), y.isEmpty());
2291 +            assertEquals(x.size(), y.size());
2292 +            assertEquals(new HashSet<Object>(x), new HashSet<Object>(y));
2293 +            if (x instanceof Deque) {
2294 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2295 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2296 +                                         y.toArray(new Object[0])));
2297 +            }
2298 +        }
2299 +    }
2300   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines