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.184 by jsr166, Wed Feb 10 00:05:20 2016 UTC vs.
Revision 1.243 by jsr166, Thu Apr 5 03:36:54 2018 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
# Line 8 | Line 9
9  
10   /*
11   * @test
12 < * @summary JSR-166 tck tests
13 < * @modules java.management
12 > * @summary JSR-166 tck tests, in a number of variations.
13 > *          The first is the conformance testing variant,
14 > *          while others also test implementation details.
15   * @build *
16 < * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
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 28 | 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;
31 import java.nio.file.Files;
32 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 39 | 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.Deque;
70   import java.util.Enumeration;
71 + import java.util.HashSet;
72   import java.util.Iterator;
73   import java.util.List;
74   import java.util.NoSuchElementException;
75   import java.util.PropertyPermission;
76 + import java.util.Set;
77   import java.util.concurrent.BlockingQueue;
78   import java.util.concurrent.Callable;
79   import java.util.concurrent.CountDownLatch;
80   import java.util.concurrent.CyclicBarrier;
81   import java.util.concurrent.ExecutionException;
82 + import java.util.concurrent.Executor;
83   import java.util.concurrent.Executors;
84   import java.util.concurrent.ExecutorService;
85   import java.util.concurrent.ForkJoinPool;
86   import java.util.concurrent.Future;
87 + import java.util.concurrent.FutureTask;
88   import java.util.concurrent.RecursiveAction;
89   import java.util.concurrent.RecursiveTask;
90 + import java.util.concurrent.RejectedExecutionException;
91   import java.util.concurrent.RejectedExecutionHandler;
92   import java.util.concurrent.Semaphore;
93 + import java.util.concurrent.ScheduledExecutorService;
94 + import java.util.concurrent.ScheduledFuture;
95 + import java.util.concurrent.SynchronousQueue;
96   import java.util.concurrent.ThreadFactory;
97 + import java.util.concurrent.ThreadLocalRandom;
98   import java.util.concurrent.ThreadPoolExecutor;
99 + import java.util.concurrent.TimeUnit;
100   import java.util.concurrent.TimeoutException;
101 + import java.util.concurrent.atomic.AtomicBoolean;
102   import java.util.concurrent.atomic.AtomicReference;
65 import java.util.regex.Matcher;
103   import java.util.regex.Pattern;
104  
68 import junit.framework.AssertionFailedError;
105   import junit.framework.Test;
106   import junit.framework.TestCase;
107   import junit.framework.TestResult;
# Line 184 | Line 220 | public class JSR166TestCase extends Test
220          Integer.getInteger("jsr166.suiteRuns", 1);
221  
222      /**
223 <     * The scaling factor to apply to standard delays used in tests.
223 >     * Returns the value of the system property, or NaN if not defined.
224       */
225 <    private static final int delayFactor =
226 <        Integer.getInteger("jsr166.delay.factor", 1);
225 >    private static float systemPropertyValue(String name) {
226 >        String floatString = System.getProperty(name);
227 >        if (floatString == null)
228 >            return Float.NaN;
229 >        try {
230 >            return Float.parseFloat(floatString);
231 >        } catch (NumberFormatException ex) {
232 >            throw new IllegalArgumentException(
233 >                String.format("Bad float value in system property %s=%s",
234 >                              name, floatString));
235 >        }
236 >    }
237 >
238 >    /**
239 >     * The scaling factor to apply to standard delays used in tests.
240 >     * May be initialized from any of:
241 >     * - the "jsr166.delay.factor" system property
242 >     * - the "test.timeout.factor" system property (as used by jtreg)
243 >     *   See: http://openjdk.java.net/jtreg/tag-spec.html
244 >     * - hard-coded fuzz factor when using a known slowpoke VM
245 >     */
246 >    private static final float delayFactor = delayFactor();
247 >
248 >    private static float delayFactor() {
249 >        float x;
250 >        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
251 >            return x;
252 >        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
253 >            return x;
254 >        String prop = System.getProperty("java.vm.version");
255 >        if (prop != null && prop.matches(".*debug.*"))
256 >            return 4.0f; // How much slower is fastdebug than product?!
257 >        return 1.0f;
258 >    }
259  
260      public JSR166TestCase() { super(); }
261      public JSR166TestCase(String name) { super(name); }
# Line 240 | Line 308 | public class JSR166TestCase extends Test
308  
309   //     public static String cpuModel() {
310   //         try {
311 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
311 > //             java.util.regex.Matcher matcher
312 > //               = Pattern.compile("model name\\s*: (.*)")
313   //                 .matcher(new String(
314 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
314 > //                     java.nio.file.Files.readAllBytes(
315 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
316   //             matcher.find();
317   //             return matcher.group(1);
318   //         } catch (Exception ex) { return null; }
# Line 351 | Line 421 | public class JSR166TestCase extends Test
421          for (String testClassName : testClassNames) {
422              try {
423                  Class<?> testClass = Class.forName(testClassName);
424 <                Method m = testClass.getDeclaredMethod("suite",
355 <                                                       new Class<?>[0]);
424 >                Method m = testClass.getDeclaredMethod("suite");
425                  suite.addTest(newTestSuite((Test)m.invoke(null)));
426 <            } catch (Exception e) {
427 <                throw new Error("Missing test class", e);
426 >            } catch (ReflectiveOperationException e) {
427 >                throw new AssertionError("Missing test class", e);
428              }
429          }
430      }
# Line 377 | Line 446 | public class JSR166TestCase extends Test
446          }
447      }
448  
449 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
450 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
451 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
452 <    public static boolean atLeastJava9() {
453 <        return JAVA_CLASS_VERSION >= 53.0
385 <            // As of 2015-09, java9 still uses 52.0 class file version
386 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
387 <    }
388 <    public static boolean atLeastJava10() {
389 <        return JAVA_CLASS_VERSION >= 54.0
390 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
391 <    }
449 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
450 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
451 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
452 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
453 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
454  
455      /**
456       * Collects all JSR166 unit tests as one suite.
# Line 409 | Line 471 | public class JSR166TestCase extends Test
471              AbstractQueuedLongSynchronizerTest.suite(),
472              ArrayBlockingQueueTest.suite(),
473              ArrayDequeTest.suite(),
474 +            ArrayListTest.suite(),
475              AtomicBooleanTest.suite(),
476              AtomicIntegerArrayTest.suite(),
477              AtomicIntegerFieldUpdaterTest.suite(),
# Line 431 | Line 494 | public class JSR166TestCase extends Test
494              CopyOnWriteArrayListTest.suite(),
495              CopyOnWriteArraySetTest.suite(),
496              CountDownLatchTest.suite(),
497 +            CountedCompleterTest.suite(),
498              CyclicBarrierTest.suite(),
499              DelayQueueTest.suite(),
500              EntryTest.suite(),
# Line 459 | Line 523 | public class JSR166TestCase extends Test
523              TreeMapTest.suite(),
524              TreeSetTest.suite(),
525              TreeSubMapTest.suite(),
526 <            TreeSubSetTest.suite());
526 >            TreeSubSetTest.suite(),
527 >            VectorTest.suite());
528  
529          // Java8+ test classes
530          if (atLeastJava8()) {
531              String[] java8TestClassNames = {
532 +                "ArrayDeque8Test",
533                  "Atomic8Test",
534                  "CompletableFutureTest",
535                  "ConcurrentHashMap8Test",
536 <                "CountedCompleterTest",
536 >                "CountedCompleter8Test",
537                  "DoubleAccumulatorTest",
538                  "DoubleAdderTest",
539                  "ForkJoinPool8Test",
540                  "ForkJoinTask8Test",
541 +                "HashMapTest",
542 +                "LinkedBlockingDeque8Test",
543 +                "LinkedBlockingQueue8Test",
544                  "LongAccumulatorTest",
545                  "LongAdderTest",
546                  "SplittableRandomTest",
547                  "StampedLockTest",
548                  "SubmissionPublisherTest",
549                  "ThreadLocalRandom8Test",
550 +                "TimeUnit8Test",
551              };
552              addNamedTestClasses(suite, java8TestClassNames);
553          }
# Line 485 | Line 555 | public class JSR166TestCase extends Test
555          // Java9+ test classes
556          if (atLeastJava9()) {
557              String[] java9TestClassNames = {
558 <                // Currently empty, but expecting varhandle tests
558 >                "AtomicBoolean9Test",
559 >                "AtomicInteger9Test",
560 >                "AtomicIntegerArray9Test",
561 >                "AtomicLong9Test",
562 >                "AtomicLongArray9Test",
563 >                "AtomicReference9Test",
564 >                "AtomicReferenceArray9Test",
565 >                "ExecutorCompletionService9Test",
566 >                "ForkJoinPool9Test",
567              };
568              addNamedTestClasses(suite, java9TestClassNames);
569          }
# Line 496 | Line 574 | public class JSR166TestCase extends Test
574      /** Returns list of junit-style test method names in given class. */
575      public static ArrayList<String> testMethodNames(Class<?> testClass) {
576          Method[] methods = testClass.getDeclaredMethods();
577 <        ArrayList<String> names = new ArrayList<String>(methods.length);
577 >        ArrayList<String> names = new ArrayList<>(methods.length);
578          for (Method method : methods) {
579              if (method.getName().startsWith("test")
580                  && Modifier.isPublic(method.getModifiers())
# Line 523 | Line 601 | public class JSR166TestCase extends Test
601              for (String methodName : testMethodNames(testClass))
602                  suite.addTest((Test) c.newInstance(data, methodName));
603              return suite;
604 <        } catch (Exception e) {
605 <            throw new Error(e);
604 >        } catch (ReflectiveOperationException e) {
605 >            throw new AssertionError(e);
606          }
607      }
608  
# Line 540 | Line 618 | public class JSR166TestCase extends Test
618          if (atLeastJava8()) {
619              String name = testClass.getName();
620              String name8 = name.replaceAll("Test$", "8Test");
621 <            if (name.equals(name8)) throw new Error(name);
621 >            if (name.equals(name8)) throw new AssertionError(name);
622              try {
623                  return (Test)
624                      Class.forName(name8)
625 <                    .getMethod("testSuite", new Class[] { dataClass })
625 >                    .getMethod("testSuite", dataClass)
626                      .invoke(null, data);
627 <            } catch (Exception e) {
628 <                throw new Error(e);
627 >            } catch (ReflectiveOperationException e) {
628 >                throw new AssertionError(e);
629              }
630          } else {
631              return new TestSuite();
# Line 561 | Line 639 | public class JSR166TestCase extends Test
639      public static long MEDIUM_DELAY_MS;
640      public static long LONG_DELAY_MS;
641  
642 +    private static final long RANDOM_TIMEOUT;
643 +    private static final long RANDOM_EXPIRED_TIMEOUT;
644 +    private static final TimeUnit RANDOM_TIMEUNIT;
645 +    static {
646 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
647 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
648 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
649 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
650 +        TimeUnit[] timeUnits = TimeUnit.values();
651 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
652 +    }
653 +
654 +    /**
655 +     * Returns a timeout for use when any value at all will do.
656 +     */
657 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
658 +
659 +    /**
660 +     * Returns a timeout that means "no waiting", i.e. not positive.
661 +     */
662 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
663 +
664 +    /**
665 +     * Returns a random non-null TimeUnit.
666 +     */
667 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
668 +
669      /**
670       * Returns the shortest timed delay. This can be scaled up for
671 <     * slow machines using the jsr166.delay.factor system property.
671 >     * slow machines using the jsr166.delay.factor system property,
672 >     * or via jtreg's -timeoutFactor: flag.
673 >     * http://openjdk.java.net/jtreg/command-help.html
674       */
675      protected long getShortDelay() {
676 <        return 50 * delayFactor;
676 >        return (long) (50 * delayFactor);
677      }
678  
679      /**
# Line 579 | Line 686 | public class JSR166TestCase extends Test
686          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
687      }
688  
689 +    private static final long TIMEOUT_DELAY_MS
690 +        = (long) (12.0 * Math.cbrt(delayFactor));
691 +
692      /**
693 <     * Returns a timeout in milliseconds to be used in tests that
694 <     * verify that operations block or time out.
693 >     * Returns a timeout in milliseconds to be used in tests that verify
694 >     * that operations block or time out.  We want this to be longer
695 >     * than the OS scheduling quantum, but not too long, so don't scale
696 >     * linearly with delayFactor; we use "crazy" cube root instead.
697       */
698 <    long timeoutMillis() {
699 <        return SHORT_DELAY_MS / 4;
698 >    static long timeoutMillis() {
699 >        return TIMEOUT_DELAY_MS;
700      }
701  
702      /**
# Line 600 | Line 712 | public class JSR166TestCase extends Test
712       * The first exception encountered if any threadAssertXXX method fails.
713       */
714      private final AtomicReference<Throwable> threadFailure
715 <        = new AtomicReference<Throwable>(null);
715 >        = new AtomicReference<>(null);
716  
717      /**
718       * Records an exception so that it can be rethrown later in the test
# Line 622 | Line 734 | public class JSR166TestCase extends Test
734          String msg = toString() + ": " + String.format(format, args);
735          System.err.println(msg);
736          dumpTestThreads();
737 <        throw new AssertionFailedError(msg);
737 >        throw new AssertionError(msg);
738      }
739  
740      /**
# Line 643 | Line 755 | public class JSR166TestCase extends Test
755                  throw (RuntimeException) t;
756              else if (t instanceof Exception)
757                  throw (Exception) t;
758 <            else {
759 <                AssertionFailedError afe =
648 <                    new AssertionFailedError(t.toString());
649 <                afe.initCause(t);
650 <                throw afe;
651 <            }
758 >            else
759 >                throw new AssertionError(t.toString(), t);
760          }
761  
762          if (Thread.interrupted())
# Line 682 | Line 790 | public class JSR166TestCase extends Test
790  
791      /**
792       * Just like fail(reason), but additionally recording (using
793 <     * threadRecordFailure) any AssertionFailedError thrown, so that
794 <     * the current testcase will fail.
793 >     * threadRecordFailure) any AssertionError thrown, so that the
794 >     * current testcase will fail.
795       */
796      public void threadFail(String reason) {
797          try {
798              fail(reason);
799 <        } catch (AssertionFailedError t) {
800 <            threadRecordFailure(t);
801 <            throw t;
799 >        } catch (AssertionError fail) {
800 >            threadRecordFailure(fail);
801 >            throw fail;
802          }
803      }
804  
805      /**
806       * Just like assertTrue(b), but additionally recording (using
807 <     * threadRecordFailure) any AssertionFailedError thrown, so that
808 <     * the current testcase will fail.
807 >     * threadRecordFailure) any AssertionError thrown, so that the
808 >     * current testcase will fail.
809       */
810      public void threadAssertTrue(boolean b) {
811          try {
812              assertTrue(b);
813 <        } catch (AssertionFailedError t) {
814 <            threadRecordFailure(t);
815 <            throw t;
813 >        } catch (AssertionError fail) {
814 >            threadRecordFailure(fail);
815 >            throw fail;
816          }
817      }
818  
819      /**
820       * Just like assertFalse(b), but additionally recording (using
821 <     * threadRecordFailure) any AssertionFailedError thrown, so that
822 <     * the current testcase will fail.
821 >     * threadRecordFailure) any AssertionError thrown, so that the
822 >     * current testcase will fail.
823       */
824      public void threadAssertFalse(boolean b) {
825          try {
826              assertFalse(b);
827 <        } catch (AssertionFailedError t) {
828 <            threadRecordFailure(t);
829 <            throw t;
827 >        } catch (AssertionError fail) {
828 >            threadRecordFailure(fail);
829 >            throw fail;
830          }
831      }
832  
833      /**
834       * Just like assertNull(x), but additionally recording (using
835 <     * threadRecordFailure) any AssertionFailedError thrown, so that
836 <     * the current testcase will fail.
835 >     * threadRecordFailure) any AssertionError thrown, so that the
836 >     * current testcase will fail.
837       */
838      public void threadAssertNull(Object x) {
839          try {
840              assertNull(x);
841 <        } catch (AssertionFailedError t) {
842 <            threadRecordFailure(t);
843 <            throw t;
841 >        } catch (AssertionError fail) {
842 >            threadRecordFailure(fail);
843 >            throw fail;
844          }
845      }
846  
847      /**
848       * Just like assertEquals(x, y), but additionally recording (using
849 <     * threadRecordFailure) any AssertionFailedError thrown, so that
850 <     * the current testcase will fail.
849 >     * threadRecordFailure) any AssertionError thrown, so that the
850 >     * current testcase will fail.
851       */
852      public void threadAssertEquals(long x, long y) {
853          try {
854              assertEquals(x, y);
855 <        } catch (AssertionFailedError t) {
856 <            threadRecordFailure(t);
857 <            throw t;
855 >        } catch (AssertionError fail) {
856 >            threadRecordFailure(fail);
857 >            throw fail;
858          }
859      }
860  
861      /**
862       * Just like assertEquals(x, y), but additionally recording (using
863 <     * threadRecordFailure) any AssertionFailedError thrown, so that
864 <     * the current testcase will fail.
863 >     * threadRecordFailure) any AssertionError thrown, so that the
864 >     * current testcase will fail.
865       */
866      public void threadAssertEquals(Object x, Object y) {
867          try {
868              assertEquals(x, y);
869 <        } catch (AssertionFailedError fail) {
869 >        } catch (AssertionError fail) {
870              threadRecordFailure(fail);
871              throw fail;
872          } catch (Throwable fail) {
# Line 768 | Line 876 | public class JSR166TestCase extends Test
876  
877      /**
878       * Just like assertSame(x, y), but additionally recording (using
879 <     * threadRecordFailure) any AssertionFailedError thrown, so that
880 <     * the current testcase will fail.
879 >     * threadRecordFailure) any AssertionError thrown, so that the
880 >     * current testcase will fail.
881       */
882      public void threadAssertSame(Object x, Object y) {
883          try {
884              assertSame(x, y);
885 <        } catch (AssertionFailedError fail) {
885 >        } catch (AssertionError fail) {
886              threadRecordFailure(fail);
887              throw fail;
888          }
# Line 796 | Line 904 | public class JSR166TestCase extends Test
904  
905      /**
906       * Records the given exception using {@link #threadRecordFailure},
907 <     * then rethrows the exception, wrapping it in an
908 <     * AssertionFailedError if necessary.
907 >     * then rethrows the exception, wrapping it in an AssertionError
908 >     * if necessary.
909       */
910      public void threadUnexpectedException(Throwable t) {
911          threadRecordFailure(t);
# Line 806 | Line 914 | public class JSR166TestCase extends Test
914              throw (RuntimeException) t;
915          else if (t instanceof Error)
916              throw (Error) t;
917 <        else {
918 <            AssertionFailedError afe =
811 <                new AssertionFailedError("unexpected exception: " + t);
812 <            afe.initCause(t);
813 <            throw afe;
814 <        }
917 >        else
918 >            throw new AssertionError("unexpected exception: " + t, t);
919      }
920  
921      /**
# Line 879 | Line 983 | public class JSR166TestCase extends Test
983          }};
984      }
985  
986 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
987 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
988 +    }
989 +
990 +    Runnable releaser(final AtomicBoolean flag) {
991 +        return new Runnable() { public void run() { flag.set(true); }};
992 +    }
993 +
994      /**
995       * Waits out termination of a thread pool or fails doing so.
996       */
# Line 902 | Line 1014 | public class JSR166TestCase extends Test
1014          }
1015      }
1016  
1017 <    /** Like Runnable, but with the freedom to throw anything */
1017 >    /**
1018 >     * Like Runnable, but with the freedom to throw anything.
1019 >     * junit folks had the same idea:
1020 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1021 >     */
1022      interface Action { public void run() throws Throwable; }
1023  
1024      /**
# Line 933 | Line 1049 | public class JSR166TestCase extends Test
1049       * Uninteresting threads are filtered out.
1050       */
1051      static void dumpTestThreads() {
1052 +        SecurityManager sm = System.getSecurityManager();
1053 +        if (sm != null) {
1054 +            try {
1055 +                System.setSecurityManager(null);
1056 +            } catch (SecurityException giveUp) {
1057 +                return;
1058 +            }
1059 +        }
1060 +
1061          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1062          System.err.println("------ stacktrace dump start ------");
1063          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1064 <            String name = info.getThreadName();
1064 >            final String name = info.getThreadName();
1065 >            String lockName;
1066              if ("Signal Dispatcher".equals(name))
1067                  continue;
1068              if ("Reference Handler".equals(name)
1069 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1069 >                && (lockName = info.getLockName()) != null
1070 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1071                  continue;
1072              if ("Finalizer".equals(name)
1073 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1073 >                && (lockName = info.getLockName()) != null
1074 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1075                  continue;
1076              if ("checkForWedgedTest".equals(name))
1077                  continue;
1078              System.err.print(info);
1079          }
1080          System.err.println("------ stacktrace dump end ------");
953    }
1081  
1082 <    /**
956 <     * Checks that thread does not terminate within the default
957 <     * millisecond delay of {@code timeoutMillis()}.
958 <     */
959 <    void assertThreadStaysAlive(Thread thread) {
960 <        assertThreadStaysAlive(thread, timeoutMillis());
1082 >        if (sm != null) System.setSecurityManager(sm);
1083      }
1084  
1085      /**
1086 <     * Checks that thread does not terminate within the given millisecond delay.
1086 >     * Checks that thread eventually enters the expected blocked thread state.
1087       */
1088 <    void assertThreadStaysAlive(Thread thread, long millis) {
1089 <        try {
1090 <            // No need to optimize the failing case via Thread.join.
1091 <            delay(millis);
1092 <            assertTrue(thread.isAlive());
1093 <        } catch (InterruptedException fail) {
1094 <            threadFail("Unexpected InterruptedException");
1095 <        }
1096 <    }
1097 <
1098 <    /**
1099 <     * Checks that the threads do not terminate within the default
1100 <     * millisecond delay of {@code timeoutMillis()}.
979 <     */
980 <    void assertThreadsStayAlive(Thread... threads) {
981 <        assertThreadsStayAlive(timeoutMillis(), threads);
982 <    }
983 <
984 <    /**
985 <     * Checks that the threads do not terminate within the given millisecond delay.
986 <     */
987 <    void assertThreadsStayAlive(long millis, Thread... threads) {
988 <        try {
989 <            // No need to optimize the failing case via Thread.join.
990 <            delay(millis);
991 <            for (Thread thread : threads)
992 <                assertTrue(thread.isAlive());
993 <        } catch (InterruptedException fail) {
994 <            threadFail("Unexpected InterruptedException");
1088 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1089 >        // always sleep at least 1 ms, with high probability avoiding
1090 >        // transitory states
1091 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1092 >            try { delay(1); }
1093 >            catch (InterruptedException fail) {
1094 >                throw new AssertionError("Unexpected InterruptedException", fail);
1095 >            }
1096 >            Thread.State s = thread.getState();
1097 >            if (s == expected)
1098 >                return;
1099 >            else if (s == Thread.State.TERMINATED)
1100 >                fail("Unexpected thread termination");
1101          }
1102 +        fail("timed out waiting for thread to enter thread state " + expected);
1103      }
1104  
1105      /**
# Line 1033 | Line 1140 | public class JSR166TestCase extends Test
1140      }
1141  
1142      /**
1143 +     * The maximum number of consecutive spurious wakeups we should
1144 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1145 +     */
1146 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1147 +
1148 +    /**
1149       * The number of elements to place in collections, arrays, etc.
1150       */
1151      public static final int SIZE = 20;
# Line 1136 | Line 1249 | public class JSR166TestCase extends Test
1249          }
1250          public void refresh() {}
1251          public String toString() {
1252 <            List<Permission> ps = new ArrayList<Permission>();
1252 >            List<Permission> ps = new ArrayList<>();
1253              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1254                  ps.add(e.nextElement());
1255              return "AdjustablePolicy with permissions " + ps;
# Line 1164 | Line 1277 | public class JSR166TestCase extends Test
1277  
1278      /**
1279       * Sleeps until the given time has elapsed.
1280 <     * Throws AssertionFailedError if interrupted.
1280 >     * Throws AssertionError if interrupted.
1281       */
1282 <    void sleep(long millis) {
1282 >    static void sleep(long millis) {
1283          try {
1284              delay(millis);
1285          } catch (InterruptedException fail) {
1286 <            AssertionFailedError afe =
1174 <                new AssertionFailedError("Unexpected InterruptedException");
1175 <            afe.initCause(fail);
1176 <            throw afe;
1286 >            throw new AssertionError("Unexpected InterruptedException", fail);
1287          }
1288      }
1289  
# Line 1182 | Line 1292 | public class JSR166TestCase extends Test
1292       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1293       */
1294      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1295 <        long startTime = System.nanoTime();
1295 >        long startTime = 0L;
1296          for (;;) {
1297              Thread.State s = thread.getState();
1298              if (s == Thread.State.BLOCKED ||
# Line 1191 | Line 1301 | public class JSR166TestCase extends Test
1301                  return;
1302              else if (s == Thread.State.TERMINATED)
1303                  fail("Unexpected thread termination");
1304 +            else if (startTime == 0L)
1305 +                startTime = System.nanoTime();
1306              else if (millisElapsedSince(startTime) > timeoutMillis) {
1307                  threadAssertTrue(thread.isAlive());
1308 <                return;
1308 >                fail("timed out waiting for thread to enter wait state");
1309              }
1310              Thread.yield();
1311          }
1312      }
1313  
1314      /**
1315 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1316 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1315 >     * Spin-waits up to the specified number of milliseconds for the given
1316 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1317 >     * and additionally satisfy the given condition.
1318 >     */
1319 >    void waitForThreadToEnterWaitState(
1320 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1321 >        long startTime = 0L;
1322 >        for (;;) {
1323 >            Thread.State s = thread.getState();
1324 >            if (s == Thread.State.BLOCKED ||
1325 >                s == Thread.State.WAITING ||
1326 >                s == Thread.State.TIMED_WAITING) {
1327 >                try {
1328 >                    if (waitingForGodot.call())
1329 >                        return;
1330 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1331 >            }
1332 >            else if (s == Thread.State.TERMINATED)
1333 >                fail("Unexpected thread termination");
1334 >            else if (startTime == 0L)
1335 >                startTime = System.nanoTime();
1336 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1337 >                threadAssertTrue(thread.isAlive());
1338 >                fail("timed out waiting for thread to enter wait state");
1339 >            }
1340 >            Thread.yield();
1341 >        }
1342 >    }
1343 >
1344 >    /**
1345 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1346 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1347       */
1348      void waitForThreadToEnterWaitState(Thread thread) {
1349          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1350      }
1351  
1352      /**
1353 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1354 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1355 +     * and additionally satisfy the given condition.
1356 +     */
1357 +    void waitForThreadToEnterWaitState(
1358 +        Thread thread, Callable<Boolean> waitingForGodot) {
1359 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1360 +    }
1361 +
1362 +    /**
1363       * Returns the number of milliseconds since time given by
1364       * startNanoTime, which must have been previously returned from a
1365       * call to {@link System#nanoTime()}.
# Line 1222 | Line 1374 | public class JSR166TestCase extends Test
1374   //             r.run();
1375   //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1376   //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1377 < //             throw new AssertionFailedError("did not return promptly");
1377 > //             throw new AssertionError("did not return promptly");
1378   //     }
1379  
1380   //     void assertTerminatesPromptly(Runnable r) {
# Line 1239 | Line 1391 | public class JSR166TestCase extends Test
1391              assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1392          } catch (Throwable fail) { threadUnexpectedException(fail); }
1393          if (millisElapsedSince(startTime) > timeoutMillis/2)
1394 <            throw new AssertionFailedError("timed get did not return promptly");
1394 >            throw new AssertionError("timed get did not return promptly");
1395      }
1396  
1397      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1297 | Line 1449 | public class JSR166TestCase extends Test
1449          }
1450      }
1451  
1300    public abstract class RunnableShouldThrow implements Runnable {
1301        protected abstract void realRun() throws Throwable;
1302
1303        final Class<?> exceptionClass;
1304
1305        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1306            this.exceptionClass = exceptionClass;
1307        }
1308
1309        public final void run() {
1310            try {
1311                realRun();
1312                threadShouldThrow(exceptionClass.getSimpleName());
1313            } catch (Throwable t) {
1314                if (! exceptionClass.isInstance(t))
1315                    threadUnexpectedException(t);
1316            }
1317        }
1318    }
1319
1452      public abstract class ThreadShouldThrow extends Thread {
1453          protected abstract void realRun() throws Throwable;
1454  
# Line 1435 | Line 1567 | public class JSR166TestCase extends Test
1567          return new LatchAwaiter(latch);
1568      }
1569  
1570 <    public void await(CountDownLatch latch) {
1570 >    public void await(CountDownLatch latch, long timeoutMillis) {
1571          try {
1572 <            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1572 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1573                  fail("timed out waiting for CountDownLatch for "
1574 <                     + (LONG_DELAY_MS/1000) + " sec");
1574 >                     + (timeoutMillis/1000) + " sec");
1575          } catch (Throwable fail) {
1576              threadUnexpectedException(fail);
1577          }
1578      }
1579  
1580 +    public void await(CountDownLatch latch) {
1581 +        await(latch, LONG_DELAY_MS);
1582 +    }
1583 +
1584      public void await(Semaphore semaphore) {
1585          try {
1586              if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
# Line 1455 | Line 1591 | public class JSR166TestCase extends Test
1591          }
1592      }
1593  
1594 +    public void await(CyclicBarrier barrier) {
1595 +        try {
1596 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1597 +        } catch (Throwable fail) {
1598 +            threadUnexpectedException(fail);
1599 +        }
1600 +    }
1601 +
1602   //     /**
1603   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1604   //      */
# Line 1469 | Line 1613 | public class JSR166TestCase extends Test
1613   //         long startTime = System.nanoTime();
1614   //         while (!flag.get()) {
1615   //             if (millisElapsedSince(startTime) > timeoutMillis)
1616 < //                 throw new AssertionFailedError("timed out");
1616 > //                 throw new AssertionError("timed out");
1617   //             Thread.yield();
1618   //         }
1619   //     }
# Line 1478 | Line 1622 | public class JSR166TestCase extends Test
1622          public String call() { throw new NullPointerException(); }
1623      }
1624  
1481    public static class CallableOne implements Callable<Integer> {
1482        public Integer call() { return one; }
1483    }
1484
1485    public class ShortRunnable extends CheckedRunnable {
1486        protected void realRun() throws Throwable {
1487            delay(SHORT_DELAY_MS);
1488        }
1489    }
1490
1491    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1492        protected void realRun() throws InterruptedException {
1493            delay(SHORT_DELAY_MS);
1494        }
1495    }
1496
1497    public class SmallRunnable extends CheckedRunnable {
1498        protected void realRun() throws Throwable {
1499            delay(SMALL_DELAY_MS);
1500        }
1501    }
1502
1625      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1626          protected void realRun() {
1627              try {
# Line 1508 | Line 1630 | public class JSR166TestCase extends Test
1630          }
1631      }
1632  
1511    public class SmallCallable extends CheckedCallable {
1512        protected Object realCall() throws InterruptedException {
1513            delay(SMALL_DELAY_MS);
1514            return Boolean.TRUE;
1515        }
1516    }
1517
1518    public class MediumRunnable extends CheckedRunnable {
1519        protected void realRun() throws Throwable {
1520            delay(MEDIUM_DELAY_MS);
1521        }
1522    }
1523
1524    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1525        protected void realRun() throws InterruptedException {
1526            delay(MEDIUM_DELAY_MS);
1527        }
1528    }
1529
1633      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1634          return new CheckedRunnable() {
1635              protected void realRun() {
# Line 1536 | Line 1639 | public class JSR166TestCase extends Test
1639              }};
1640      }
1641  
1539    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1540        protected void realRun() {
1541            try {
1542                delay(MEDIUM_DELAY_MS);
1543            } catch (InterruptedException ok) {}
1544        }
1545    }
1546
1547    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1548        protected void realRun() {
1549            try {
1550                delay(LONG_DELAY_MS);
1551            } catch (InterruptedException ok) {}
1552        }
1553    }
1554
1642      /**
1643       * For use as ThreadFactory in constructors
1644       */
# Line 1565 | Line 1652 | public class JSR166TestCase extends Test
1652          boolean isDone();
1653      }
1654  
1568    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1569        return new TrackedRunnable() {
1570                private volatile boolean done = false;
1571                public boolean isDone() { return done; }
1572                public void run() {
1573                    try {
1574                        delay(timeoutMillis);
1575                        done = true;
1576                    } catch (InterruptedException ok) {}
1577                }
1578            };
1579    }
1580
1581    public static class TrackedShortRunnable implements Runnable {
1582        public volatile boolean done = false;
1583        public void run() {
1584            try {
1585                delay(SHORT_DELAY_MS);
1586                done = true;
1587            } catch (InterruptedException ok) {}
1588        }
1589    }
1590
1591    public static class TrackedSmallRunnable implements Runnable {
1592        public volatile boolean done = false;
1593        public void run() {
1594            try {
1595                delay(SMALL_DELAY_MS);
1596                done = true;
1597            } catch (InterruptedException ok) {}
1598        }
1599    }
1600
1601    public static class TrackedMediumRunnable implements Runnable {
1602        public volatile boolean done = false;
1603        public void run() {
1604            try {
1605                delay(MEDIUM_DELAY_MS);
1606                done = true;
1607            } catch (InterruptedException ok) {}
1608        }
1609    }
1610
1611    public static class TrackedLongRunnable implements Runnable {
1612        public volatile boolean done = false;
1613        public void run() {
1614            try {
1615                delay(LONG_DELAY_MS);
1616                done = true;
1617            } catch (InterruptedException ok) {}
1618        }
1619    }
1620
1655      public static class TrackedNoOpRunnable implements Runnable {
1656          public volatile boolean done = false;
1657          public void run() {
# Line 1625 | Line 1659 | public class JSR166TestCase extends Test
1659          }
1660      }
1661  
1628    public static class TrackedCallable implements Callable {
1629        public volatile boolean done = false;
1630        public Object call() {
1631            try {
1632                delay(SMALL_DELAY_MS);
1633                done = true;
1634            } catch (InterruptedException ok) {}
1635            return Boolean.TRUE;
1636        }
1637    }
1638
1662      /**
1663       * Analog of CheckedRunnable for RecursiveAction
1664       */
# Line 1677 | Line 1700 | public class JSR166TestCase extends Test
1700  
1701      /**
1702       * A CyclicBarrier that uses timed await and fails with
1703 <     * AssertionFailedErrors instead of throwing checked exceptions.
1703 >     * AssertionErrors instead of throwing checked exceptions.
1704       */
1705 <    public class CheckedBarrier extends CyclicBarrier {
1705 >    public static class CheckedBarrier extends CyclicBarrier {
1706          public CheckedBarrier(int parties) { super(parties); }
1707  
1708          public int await() {
1709              try {
1710                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1711              } catch (TimeoutException timedOut) {
1712 <                throw new AssertionFailedError("timed out");
1712 >                throw new AssertionError("timed out");
1713              } catch (Exception fail) {
1714 <                AssertionFailedError afe =
1692 <                    new AssertionFailedError("Unexpected exception: " + fail);
1693 <                afe.initCause(fail);
1694 <                throw afe;
1714 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1715              }
1716          }
1717      }
# Line 1702 | Line 1722 | public class JSR166TestCase extends Test
1722              assertEquals(0, q.size());
1723              assertNull(q.peek());
1724              assertNull(q.poll());
1725 <            assertNull(q.poll(0, MILLISECONDS));
1725 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1726              assertEquals(q.toString(), "[]");
1727              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1728              assertFalse(q.iterator().hasNext());
# Line 1743 | Line 1763 | public class JSR166TestCase extends Test
1763          }
1764      }
1765  
1766 +    void assertImmutable(final Object o) {
1767 +        if (o instanceof Collection) {
1768 +            assertThrows(
1769 +                UnsupportedOperationException.class,
1770 +                new Runnable() { public void run() {
1771 +                        ((Collection) o).add(null);}});
1772 +        }
1773 +    }
1774 +
1775      @SuppressWarnings("unchecked")
1776      <T> T serialClone(T o) {
1777          try {
1778              ObjectInputStream ois = new ObjectInputStream
1779                  (new ByteArrayInputStream(serialBytes(o)));
1780              T clone = (T) ois.readObject();
1781 +            if (o == clone) assertImmutable(o);
1782              assertSame(o.getClass(), clone.getClass());
1783              return clone;
1784          } catch (Throwable fail) {
# Line 1757 | Line 1787 | public class JSR166TestCase extends Test
1787          }
1788      }
1789  
1790 +    /**
1791 +     * A version of serialClone that leaves error handling (for
1792 +     * e.g. NotSerializableException) up to the caller.
1793 +     */
1794 +    @SuppressWarnings("unchecked")
1795 +    <T> T serialClonePossiblyFailing(T o)
1796 +        throws ReflectiveOperationException, java.io.IOException {
1797 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1798 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1799 +        oos.writeObject(o);
1800 +        oos.flush();
1801 +        oos.close();
1802 +        ObjectInputStream ois = new ObjectInputStream
1803 +            (new ByteArrayInputStream(bos.toByteArray()));
1804 +        T clone = (T) ois.readObject();
1805 +        if (o == clone) assertImmutable(o);
1806 +        assertSame(o.getClass(), clone.getClass());
1807 +        return clone;
1808 +    }
1809 +
1810 +    /**
1811 +     * If o implements Cloneable and has a public clone method,
1812 +     * returns a clone of o, else null.
1813 +     */
1814 +    @SuppressWarnings("unchecked")
1815 +    <T> T cloneableClone(T o) {
1816 +        if (!(o instanceof Cloneable)) return null;
1817 +        final T clone;
1818 +        try {
1819 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1820 +        } catch (NoSuchMethodException ok) {
1821 +            return null;
1822 +        } catch (ReflectiveOperationException unexpected) {
1823 +            throw new Error(unexpected);
1824 +        }
1825 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1826 +        assertSame(o.getClass(), clone.getClass());
1827 +        return clone;
1828 +    }
1829 +
1830      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1831                               Runnable... throwingActions) {
1832          for (Runnable throwingAction : throwingActions) {
# Line 1764 | Line 1834 | public class JSR166TestCase extends Test
1834              try { throwingAction.run(); }
1835              catch (Throwable t) {
1836                  threw = true;
1837 <                if (!expectedExceptionClass.isInstance(t)) {
1838 <                    AssertionFailedError afe =
1839 <                        new AssertionFailedError
1840 <                        ("Expected " + expectedExceptionClass.getName() +
1841 <                         ", got " + t.getClass().getName());
1772 <                    afe.initCause(t);
1773 <                    threadUnexpectedException(afe);
1774 <                }
1837 >                if (!expectedExceptionClass.isInstance(t))
1838 >                    throw new AssertionError(
1839 >                            "Expected " + expectedExceptionClass.getName() +
1840 >                            ", got " + t.getClass().getName(),
1841 >                            t);
1842              }
1843              if (!threw)
1844                  shouldThrow(expectedExceptionClass.getName());
# Line 1785 | Line 1852 | public class JSR166TestCase extends Test
1852          } catch (NoSuchElementException success) {}
1853          assertFalse(it.hasNext());
1854      }
1855 +
1856 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1857 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1858 +    }
1859 +
1860 +    public Runnable runnableThrowing(final RuntimeException ex) {
1861 +        return new Runnable() { public void run() { throw ex; }};
1862 +    }
1863 +
1864 +    /** A reusable thread pool to be shared by tests. */
1865 +    static final ExecutorService cachedThreadPool =
1866 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1867 +                               1000L, MILLISECONDS,
1868 +                               new SynchronousQueue<Runnable>());
1869 +
1870 +    static <T> void shuffle(T[] array) {
1871 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1872 +    }
1873 +
1874 +    /**
1875 +     * Returns the same String as would be returned by {@link
1876 +     * Object#toString}, whether or not the given object's class
1877 +     * overrides toString().
1878 +     *
1879 +     * @see System#identityHashCode
1880 +     */
1881 +    static String identityString(Object x) {
1882 +        return x.getClass().getName()
1883 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1884 +    }
1885 +
1886 +    // --- Shared assertions for Executor tests ---
1887 +
1888 +    /**
1889 +     * Returns maximum number of tasks that can be submitted to given
1890 +     * pool (with bounded queue) before saturation (when submission
1891 +     * throws RejectedExecutionException).
1892 +     */
1893 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1894 +        BlockingQueue<Runnable> q = pool.getQueue();
1895 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1896 +    }
1897 +
1898 +    @SuppressWarnings("FutureReturnValueIgnored")
1899 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1900 +        try {
1901 +            e.execute((Runnable) null);
1902 +            shouldThrow();
1903 +        } catch (NullPointerException success) {}
1904 +
1905 +        if (! (e instanceof ExecutorService)) return;
1906 +        ExecutorService es = (ExecutorService) e;
1907 +        try {
1908 +            es.submit((Runnable) null);
1909 +            shouldThrow();
1910 +        } catch (NullPointerException success) {}
1911 +        try {
1912 +            es.submit((Runnable) null, Boolean.TRUE);
1913 +            shouldThrow();
1914 +        } catch (NullPointerException success) {}
1915 +        try {
1916 +            es.submit((Callable) null);
1917 +            shouldThrow();
1918 +        } catch (NullPointerException success) {}
1919 +
1920 +        if (! (e instanceof ScheduledExecutorService)) return;
1921 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1922 +        try {
1923 +            ses.schedule((Runnable) null,
1924 +                         randomTimeout(), randomTimeUnit());
1925 +            shouldThrow();
1926 +        } catch (NullPointerException success) {}
1927 +        try {
1928 +            ses.schedule((Callable) null,
1929 +                         randomTimeout(), randomTimeUnit());
1930 +            shouldThrow();
1931 +        } catch (NullPointerException success) {}
1932 +        try {
1933 +            ses.scheduleAtFixedRate((Runnable) null,
1934 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1935 +            shouldThrow();
1936 +        } catch (NullPointerException success) {}
1937 +        try {
1938 +            ses.scheduleWithFixedDelay((Runnable) null,
1939 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1940 +            shouldThrow();
1941 +        } catch (NullPointerException success) {}
1942 +    }
1943 +
1944 +    void setRejectedExecutionHandler(
1945 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1946 +        p.setRejectedExecutionHandler(handler);
1947 +        assertSame(handler, p.getRejectedExecutionHandler());
1948 +    }
1949 +
1950 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1951 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1952 +        final long savedTaskCount = p.getTaskCount();
1953 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1954 +        final int savedQueueSize = p.getQueue().size();
1955 +        final boolean stock = (p.getClass().getClassLoader() == null);
1956 +
1957 +        Runnable r = () -> {};
1958 +        Callable<Boolean> c = () -> Boolean.TRUE;
1959 +
1960 +        class Recorder implements RejectedExecutionHandler {
1961 +            public volatile Runnable r = null;
1962 +            public volatile ThreadPoolExecutor p = null;
1963 +            public void reset() { r = null; p = null; }
1964 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1965 +                assertNull(this.r);
1966 +                assertNull(this.p);
1967 +                this.r = r;
1968 +                this.p = p;
1969 +            }
1970 +        }
1971 +
1972 +        // check custom handler is invoked exactly once per task
1973 +        Recorder recorder = new Recorder();
1974 +        setRejectedExecutionHandler(p, recorder);
1975 +        for (int i = 2; i--> 0; ) {
1976 +            recorder.reset();
1977 +            p.execute(r);
1978 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
1979 +                assertSame(r, recorder.r);
1980 +            assertSame(p, recorder.p);
1981 +
1982 +            recorder.reset();
1983 +            assertFalse(p.submit(r).isDone());
1984 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1985 +            assertSame(p, recorder.p);
1986 +
1987 +            recorder.reset();
1988 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
1989 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1990 +            assertSame(p, recorder.p);
1991 +
1992 +            recorder.reset();
1993 +            assertFalse(p.submit(c).isDone());
1994 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1995 +            assertSame(p, recorder.p);
1996 +
1997 +            if (p instanceof ScheduledExecutorService) {
1998 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
1999 +                ScheduledFuture<?> future;
2000 +
2001 +                recorder.reset();
2002 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2003 +                assertFalse(future.isDone());
2004 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2005 +                assertSame(p, recorder.p);
2006 +
2007 +                recorder.reset();
2008 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2009 +                assertFalse(future.isDone());
2010 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2011 +                assertSame(p, recorder.p);
2012 +
2013 +                recorder.reset();
2014 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2015 +                assertFalse(future.isDone());
2016 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2017 +                assertSame(p, recorder.p);
2018 +
2019 +                recorder.reset();
2020 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2021 +                assertFalse(future.isDone());
2022 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2023 +                assertSame(p, recorder.p);
2024 +            }
2025 +        }
2026 +
2027 +        // Checking our custom handler above should be sufficient, but
2028 +        // we add some integration tests of standard handlers.
2029 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2030 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2031 +
2032 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2033 +        try {
2034 +            p.execute(setThread);
2035 +            shouldThrow();
2036 +        } catch (RejectedExecutionException success) {}
2037 +        assertNull(thread.get());
2038 +
2039 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2040 +        p.execute(setThread);
2041 +        assertNull(thread.get());
2042 +
2043 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2044 +        p.execute(setThread);
2045 +        if (p.isShutdown())
2046 +            assertNull(thread.get());
2047 +        else
2048 +            assertSame(Thread.currentThread(), thread.get());
2049 +
2050 +        setRejectedExecutionHandler(p, savedHandler);
2051 +
2052 +        // check that pool was not perturbed by handlers
2053 +        assertEquals(savedTaskCount, p.getTaskCount());
2054 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2055 +        assertEquals(savedQueueSize, p.getQueue().size());
2056 +    }
2057 +
2058 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2059 +        assertEquals(x, y);
2060 +        assertEquals(y, x);
2061 +        assertEquals(x.isEmpty(), y.isEmpty());
2062 +        assertEquals(x.size(), y.size());
2063 +        if (x instanceof List) {
2064 +            assertEquals(x.toString(), y.toString());
2065 +        }
2066 +        if (x instanceof List || x instanceof Set) {
2067 +            assertEquals(x.hashCode(), y.hashCode());
2068 +        }
2069 +        if (x instanceof List || x instanceof Deque) {
2070 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2071 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2072 +                                     y.toArray(new Object[0])));
2073 +        }
2074 +    }
2075 +
2076 +    /**
2077 +     * A weaker form of assertCollectionsEquals which does not insist
2078 +     * that the two collections satisfy Object#equals(Object), since
2079 +     * they may use identity semantics as Deques do.
2080 +     */
2081 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2082 +        if (x instanceof List || x instanceof Set)
2083 +            assertCollectionsEquals(x, y);
2084 +        else {
2085 +            assertEquals(x.isEmpty(), y.isEmpty());
2086 +            assertEquals(x.size(), y.size());
2087 +            assertEquals(new HashSet(x), new HashSet(y));
2088 +            if (x instanceof Deque) {
2089 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2090 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2091 +                                         y.toArray(new Object[0])));
2092 +            }
2093 +        }
2094 +    }
2095   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines