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.220 by jsr166, Sat Mar 11 17:33:32 2017 UTC vs.
Revision 1.244 by jsr166, Tue Apr 10 18:09:58 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 (conformance testing mode)
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
15 */
16
17 /*
18 * @test
19 * @summary JSR-166 tck tests (whitebox tests allowed)
20 * @build *
21 * @modules java.base/java.util.concurrent:open
22 *          java.base/java.lang:open
23 *          java.management
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   */
# Line 64 | Line 66 | 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;
103   import java.util.regex.Pattern;
104  
94 import junit.framework.AssertionFailedError;
105   import junit.framework.Test;
106   import junit.framework.TestCase;
107   import junit.framework.TestResult;
# Line 411 | 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",
415 <                                                       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 437 | 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
454 <            // As of 2015-09, java9 still uses 52.0 class file version
446 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
447 <    }
448 <    public static boolean atLeastJava10() {
449 <        return JAVA_CLASS_VERSION >= 54.0
450 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
451 <    }
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 >    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
455  
456      /**
457       * Collects all JSR166 unit tests as one suite.
# Line 536 | Line 539 | public class JSR166TestCase extends Test
539                  "DoubleAdderTest",
540                  "ForkJoinPool8Test",
541                  "ForkJoinTask8Test",
542 +                "HashMapTest",
543                  "LinkedBlockingDeque8Test",
544                  "LinkedBlockingQueue8Test",
545                  "LongAccumulatorTest",
# Line 598 | Line 602 | public class JSR166TestCase extends Test
602              for (String methodName : testMethodNames(testClass))
603                  suite.addTest((Test) c.newInstance(data, methodName));
604              return suite;
605 <        } catch (Exception e) {
606 <            throw new Error(e);
605 >        } catch (ReflectiveOperationException e) {
606 >            throw new AssertionError(e);
607          }
608      }
609  
# Line 615 | Line 619 | public class JSR166TestCase extends Test
619          if (atLeastJava8()) {
620              String name = testClass.getName();
621              String name8 = name.replaceAll("Test$", "8Test");
622 <            if (name.equals(name8)) throw new Error(name);
622 >            if (name.equals(name8)) throw new AssertionError(name);
623              try {
624                  return (Test)
625                      Class.forName(name8)
626 <                    .getMethod("testSuite", new Class[] { dataClass })
626 >                    .getMethod("testSuite", dataClass)
627                      .invoke(null, data);
628 <            } catch (Exception e) {
629 <                throw new Error(e);
628 >            } catch (ReflectiveOperationException e) {
629 >                throw new AssertionError(e);
630              }
631          } else {
632              return new TestSuite();
# Line 636 | Line 640 | public class JSR166TestCase extends Test
640      public static long MEDIUM_DELAY_MS;
641      public static long LONG_DELAY_MS;
642  
643 +    private static final long RANDOM_TIMEOUT;
644 +    private static final long RANDOM_EXPIRED_TIMEOUT;
645 +    private static final TimeUnit RANDOM_TIMEUNIT;
646 +    static {
647 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
648 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
649 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
650 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
651 +        TimeUnit[] timeUnits = TimeUnit.values();
652 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
653 +    }
654 +
655 +    /**
656 +     * Returns a timeout for use when any value at all will do.
657 +     */
658 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
659 +
660 +    /**
661 +     * Returns a timeout that means "no waiting", i.e. not positive.
662 +     */
663 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
664 +
665 +    /**
666 +     * Returns a random non-null TimeUnit.
667 +     */
668 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
669 +
670      /**
671       * Returns the shortest timed delay. This can be scaled up for
672       * slow machines using the jsr166.delay.factor system property,
# Line 656 | Line 687 | public class JSR166TestCase extends Test
687          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
688      }
689  
690 +    private static final long TIMEOUT_DELAY_MS
691 +        = (long) (12.0 * Math.cbrt(delayFactor));
692 +
693      /**
694 <     * Returns a timeout in milliseconds to be used in tests that
695 <     * verify that operations block or time out.
694 >     * Returns a timeout in milliseconds to be used in tests that verify
695 >     * that operations block or time out.  We want this to be longer
696 >     * than the OS scheduling quantum, but not too long, so don't scale
697 >     * linearly with delayFactor; we use "crazy" cube root instead.
698       */
699 <    long timeoutMillis() {
700 <        return SHORT_DELAY_MS / 4;
699 >    static long timeoutMillis() {
700 >        return TIMEOUT_DELAY_MS;
701      }
702  
703      /**
# Line 699 | Line 735 | public class JSR166TestCase extends Test
735          String msg = toString() + ": " + String.format(format, args);
736          System.err.println(msg);
737          dumpTestThreads();
738 <        throw new AssertionFailedError(msg);
738 >        throw new AssertionError(msg);
739      }
740  
741      /**
# Line 720 | Line 756 | public class JSR166TestCase extends Test
756                  throw (RuntimeException) t;
757              else if (t instanceof Exception)
758                  throw (Exception) t;
759 <            else {
760 <                AssertionFailedError afe =
725 <                    new AssertionFailedError(t.toString());
726 <                afe.initCause(t);
727 <                throw afe;
728 <            }
759 >            else
760 >                throw new AssertionError(t.toString(), t);
761          }
762  
763          if (Thread.interrupted())
# Line 759 | Line 791 | public class JSR166TestCase extends Test
791  
792      /**
793       * Just like fail(reason), but additionally recording (using
794 <     * threadRecordFailure) any AssertionFailedError thrown, so that
795 <     * the current testcase will fail.
794 >     * threadRecordFailure) any AssertionError thrown, so that the
795 >     * current testcase will fail.
796       */
797      public void threadFail(String reason) {
798          try {
799              fail(reason);
800 <        } catch (AssertionFailedError t) {
801 <            threadRecordFailure(t);
802 <            throw t;
800 >        } catch (AssertionError fail) {
801 >            threadRecordFailure(fail);
802 >            throw fail;
803          }
804      }
805  
806      /**
807       * Just like assertTrue(b), but additionally recording (using
808 <     * threadRecordFailure) any AssertionFailedError thrown, so that
809 <     * the current testcase will fail.
808 >     * threadRecordFailure) any AssertionError thrown, so that the
809 >     * current testcase will fail.
810       */
811      public void threadAssertTrue(boolean b) {
812          try {
813              assertTrue(b);
814 <        } catch (AssertionFailedError t) {
815 <            threadRecordFailure(t);
816 <            throw t;
814 >        } catch (AssertionError fail) {
815 >            threadRecordFailure(fail);
816 >            throw fail;
817          }
818      }
819  
820      /**
821       * Just like assertFalse(b), but additionally recording (using
822 <     * threadRecordFailure) any AssertionFailedError thrown, so that
823 <     * the current testcase will fail.
822 >     * threadRecordFailure) any AssertionError thrown, so that the
823 >     * current testcase will fail.
824       */
825      public void threadAssertFalse(boolean b) {
826          try {
827              assertFalse(b);
828 <        } catch (AssertionFailedError t) {
829 <            threadRecordFailure(t);
830 <            throw t;
828 >        } catch (AssertionError fail) {
829 >            threadRecordFailure(fail);
830 >            throw fail;
831          }
832      }
833  
834      /**
835       * Just like assertNull(x), but additionally recording (using
836 <     * threadRecordFailure) any AssertionFailedError thrown, so that
837 <     * the current testcase will fail.
836 >     * threadRecordFailure) any AssertionError thrown, so that the
837 >     * current testcase will fail.
838       */
839      public void threadAssertNull(Object x) {
840          try {
841              assertNull(x);
842 <        } catch (AssertionFailedError t) {
843 <            threadRecordFailure(t);
844 <            throw t;
842 >        } catch (AssertionError fail) {
843 >            threadRecordFailure(fail);
844 >            throw fail;
845          }
846      }
847  
848      /**
849       * Just like assertEquals(x, y), but additionally recording (using
850 <     * threadRecordFailure) any AssertionFailedError thrown, so that
851 <     * the current testcase will fail.
850 >     * threadRecordFailure) any AssertionError thrown, so that the
851 >     * current testcase will fail.
852       */
853      public void threadAssertEquals(long x, long y) {
854          try {
855              assertEquals(x, y);
856 <        } catch (AssertionFailedError t) {
857 <            threadRecordFailure(t);
858 <            throw t;
856 >        } catch (AssertionError fail) {
857 >            threadRecordFailure(fail);
858 >            throw fail;
859          }
860      }
861  
862      /**
863       * Just like assertEquals(x, y), but additionally recording (using
864 <     * threadRecordFailure) any AssertionFailedError thrown, so that
865 <     * the current testcase will fail.
864 >     * threadRecordFailure) any AssertionError thrown, so that the
865 >     * current testcase will fail.
866       */
867      public void threadAssertEquals(Object x, Object y) {
868          try {
869              assertEquals(x, y);
870 <        } catch (AssertionFailedError fail) {
870 >        } catch (AssertionError fail) {
871              threadRecordFailure(fail);
872              throw fail;
873          } catch (Throwable fail) {
# Line 845 | Line 877 | public class JSR166TestCase extends Test
877  
878      /**
879       * Just like assertSame(x, y), but additionally recording (using
880 <     * threadRecordFailure) any AssertionFailedError thrown, so that
881 <     * the current testcase will fail.
880 >     * threadRecordFailure) any AssertionError thrown, so that the
881 >     * current testcase will fail.
882       */
883      public void threadAssertSame(Object x, Object y) {
884          try {
885              assertSame(x, y);
886 <        } catch (AssertionFailedError fail) {
886 >        } catch (AssertionError fail) {
887              threadRecordFailure(fail);
888              throw fail;
889          }
# Line 873 | Line 905 | public class JSR166TestCase extends Test
905  
906      /**
907       * Records the given exception using {@link #threadRecordFailure},
908 <     * then rethrows the exception, wrapping it in an
909 <     * AssertionFailedError if necessary.
908 >     * then rethrows the exception, wrapping it in an AssertionError
909 >     * if necessary.
910       */
911      public void threadUnexpectedException(Throwable t) {
912          threadRecordFailure(t);
# Line 883 | Line 915 | public class JSR166TestCase extends Test
915              throw (RuntimeException) t;
916          else if (t instanceof Error)
917              throw (Error) t;
918 <        else {
919 <            AssertionFailedError afe =
888 <                new AssertionFailedError("unexpected exception: " + t);
889 <            afe.initCause(t);
890 <            throw afe;
891 <        }
918 >        else
919 >            throw new AssertionError("unexpected exception: " + t, t);
920      }
921  
922      /**
# Line 1056 | Line 1084 | public class JSR166TestCase extends Test
1084      }
1085  
1086      /**
1087 <     * Checks that thread does not terminate within the default
1060 <     * millisecond delay of {@code timeoutMillis()}.
1061 <     */
1062 <    void assertThreadStaysAlive(Thread thread) {
1063 <        assertThreadStaysAlive(thread, timeoutMillis());
1064 <    }
1065 <
1066 <    /**
1067 <     * Checks that thread does not terminate within the given millisecond delay.
1068 <     */
1069 <    void assertThreadStaysAlive(Thread thread, long millis) {
1070 <        try {
1071 <            // No need to optimize the failing case via Thread.join.
1072 <            delay(millis);
1073 <            assertTrue(thread.isAlive());
1074 <        } catch (InterruptedException fail) {
1075 <            threadFail("Unexpected InterruptedException");
1076 <        }
1077 <    }
1078 <
1079 <    /**
1080 <     * Checks that the threads do not terminate within the default
1081 <     * millisecond delay of {@code timeoutMillis()}.
1087 >     * Checks that thread eventually enters the expected blocked thread state.
1088       */
1089 <    void assertThreadsStayAlive(Thread... threads) {
1090 <        assertThreadsStayAlive(timeoutMillis(), threads);
1091 <    }
1092 <
1093 <    /**
1094 <     * Checks that the threads do not terminate within the given millisecond delay.
1095 <     */
1096 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1097 <        try {
1098 <            // No need to optimize the failing case via Thread.join.
1099 <            delay(millis);
1100 <            for (Thread thread : threads)
1101 <                assertTrue(thread.isAlive());
1096 <        } catch (InterruptedException fail) {
1097 <            threadFail("Unexpected InterruptedException");
1089 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1090 >        // always sleep at least 1 ms, with high probability avoiding
1091 >        // transitory states
1092 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1093 >            try { delay(1); }
1094 >            catch (InterruptedException fail) {
1095 >                throw new AssertionError("Unexpected InterruptedException", fail);
1096 >            }
1097 >            Thread.State s = thread.getState();
1098 >            if (s == expected)
1099 >                return;
1100 >            else if (s == Thread.State.TERMINATED)
1101 >                fail("Unexpected thread termination");
1102          }
1103 +        fail("timed out waiting for thread to enter thread state " + expected);
1104      }
1105  
1106      /**
# Line 1136 | Line 1141 | public class JSR166TestCase extends Test
1141      }
1142  
1143      /**
1144 +     * The maximum number of consecutive spurious wakeups we should
1145 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1146 +     */
1147 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1148 +
1149 +    /**
1150       * The number of elements to place in collections, arrays, etc.
1151       */
1152      public static final int SIZE = 20;
# Line 1267 | Line 1278 | public class JSR166TestCase extends Test
1278  
1279      /**
1280       * Sleeps until the given time has elapsed.
1281 <     * Throws AssertionFailedError if interrupted.
1281 >     * Throws AssertionError if interrupted.
1282       */
1283      static void sleep(long millis) {
1284          try {
1285              delay(millis);
1286          } catch (InterruptedException fail) {
1287 <            AssertionFailedError afe =
1277 <                new AssertionFailedError("Unexpected InterruptedException");
1278 <            afe.initCause(fail);
1279 <            throw afe;
1287 >            throw new AssertionError("Unexpected InterruptedException", fail);
1288          }
1289      }
1290  
# Line 1367 | Line 1375 | public class JSR166TestCase extends Test
1375   //             r.run();
1376   //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1377   //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1378 < //             throw new AssertionFailedError("did not return promptly");
1378 > //             throw new AssertionError("did not return promptly");
1379   //     }
1380  
1381   //     void assertTerminatesPromptly(Runnable r) {
# Line 1384 | Line 1392 | public class JSR166TestCase extends Test
1392              assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1393          } catch (Throwable fail) { threadUnexpectedException(fail); }
1394          if (millisElapsedSince(startTime) > timeoutMillis/2)
1395 <            throw new AssertionFailedError("timed get did not return promptly");
1395 >            throw new AssertionError("timed get did not return promptly");
1396      }
1397  
1398      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1442 | Line 1450 | public class JSR166TestCase extends Test
1450          }
1451      }
1452  
1445    public abstract class RunnableShouldThrow implements Runnable {
1446        protected abstract void realRun() throws Throwable;
1447
1448        final Class<?> exceptionClass;
1449
1450        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1451            this.exceptionClass = exceptionClass;
1452        }
1453
1454        public final void run() {
1455            try {
1456                realRun();
1457                threadShouldThrow(exceptionClass.getSimpleName());
1458            } catch (Throwable t) {
1459                if (! exceptionClass.isInstance(t))
1460                    threadUnexpectedException(t);
1461            }
1462        }
1463    }
1464
1453      public abstract class ThreadShouldThrow extends Thread {
1454          protected abstract void realRun() throws Throwable;
1455  
# Line 1604 | Line 1592 | public class JSR166TestCase extends Test
1592          }
1593      }
1594  
1595 +    public void await(CyclicBarrier barrier) {
1596 +        try {
1597 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1598 +        } catch (Throwable fail) {
1599 +            threadUnexpectedException(fail);
1600 +        }
1601 +    }
1602 +
1603   //     /**
1604   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1605   //      */
# Line 1618 | Line 1614 | public class JSR166TestCase extends Test
1614   //         long startTime = System.nanoTime();
1615   //         while (!flag.get()) {
1616   //             if (millisElapsedSince(startTime) > timeoutMillis)
1617 < //                 throw new AssertionFailedError("timed out");
1617 > //                 throw new AssertionError("timed out");
1618   //             Thread.yield();
1619   //         }
1620   //     }
# Line 1627 | Line 1623 | public class JSR166TestCase extends Test
1623          public String call() { throw new NullPointerException(); }
1624      }
1625  
1630    public static class CallableOne implements Callable<Integer> {
1631        public Integer call() { return one; }
1632    }
1633
1634    public class ShortRunnable extends CheckedRunnable {
1635        protected void realRun() throws Throwable {
1636            delay(SHORT_DELAY_MS);
1637        }
1638    }
1639
1640    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1641        protected void realRun() throws InterruptedException {
1642            delay(SHORT_DELAY_MS);
1643        }
1644    }
1645
1646    public class SmallRunnable extends CheckedRunnable {
1647        protected void realRun() throws Throwable {
1648            delay(SMALL_DELAY_MS);
1649        }
1650    }
1651
1626      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1627          protected void realRun() {
1628              try {
# Line 1657 | Line 1631 | public class JSR166TestCase extends Test
1631          }
1632      }
1633  
1660    public class SmallCallable extends CheckedCallable {
1661        protected Object realCall() throws InterruptedException {
1662            delay(SMALL_DELAY_MS);
1663            return Boolean.TRUE;
1664        }
1665    }
1666
1667    public class MediumRunnable extends CheckedRunnable {
1668        protected void realRun() throws Throwable {
1669            delay(MEDIUM_DELAY_MS);
1670        }
1671    }
1672
1673    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1674        protected void realRun() throws InterruptedException {
1675            delay(MEDIUM_DELAY_MS);
1676        }
1677    }
1678
1634      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1635          return new CheckedRunnable() {
1636              protected void realRun() {
# Line 1685 | Line 1640 | public class JSR166TestCase extends Test
1640              }};
1641      }
1642  
1688    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1689        protected void realRun() {
1690            try {
1691                delay(MEDIUM_DELAY_MS);
1692            } catch (InterruptedException ok) {}
1693        }
1694    }
1695
1696    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1697        protected void realRun() {
1698            try {
1699                delay(LONG_DELAY_MS);
1700            } catch (InterruptedException ok) {}
1701        }
1702    }
1703
1643      /**
1644       * For use as ThreadFactory in constructors
1645       */
# Line 1714 | Line 1653 | public class JSR166TestCase extends Test
1653          boolean isDone();
1654      }
1655  
1717    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1718        return new TrackedRunnable() {
1719                private volatile boolean done = false;
1720                public boolean isDone() { return done; }
1721                public void run() {
1722                    try {
1723                        delay(timeoutMillis);
1724                        done = true;
1725                    } catch (InterruptedException ok) {}
1726                }
1727            };
1728    }
1729
1730    public static class TrackedShortRunnable implements Runnable {
1731        public volatile boolean done = false;
1732        public void run() {
1733            try {
1734                delay(SHORT_DELAY_MS);
1735                done = true;
1736            } catch (InterruptedException ok) {}
1737        }
1738    }
1739
1740    public static class TrackedSmallRunnable implements Runnable {
1741        public volatile boolean done = false;
1742        public void run() {
1743            try {
1744                delay(SMALL_DELAY_MS);
1745                done = true;
1746            } catch (InterruptedException ok) {}
1747        }
1748    }
1749
1750    public static class TrackedMediumRunnable implements Runnable {
1751        public volatile boolean done = false;
1752        public void run() {
1753            try {
1754                delay(MEDIUM_DELAY_MS);
1755                done = true;
1756            } catch (InterruptedException ok) {}
1757        }
1758    }
1759
1760    public static class TrackedLongRunnable implements Runnable {
1761        public volatile boolean done = false;
1762        public void run() {
1763            try {
1764                delay(LONG_DELAY_MS);
1765                done = true;
1766            } catch (InterruptedException ok) {}
1767        }
1768    }
1769
1656      public static class TrackedNoOpRunnable implements Runnable {
1657          public volatile boolean done = false;
1658          public void run() {
# Line 1774 | Line 1660 | public class JSR166TestCase extends Test
1660          }
1661      }
1662  
1777    public static class TrackedCallable implements Callable {
1778        public volatile boolean done = false;
1779        public Object call() {
1780            try {
1781                delay(SMALL_DELAY_MS);
1782                done = true;
1783            } catch (InterruptedException ok) {}
1784            return Boolean.TRUE;
1785        }
1786    }
1787
1663      /**
1664       * Analog of CheckedRunnable for RecursiveAction
1665       */
# Line 1826 | Line 1701 | public class JSR166TestCase extends Test
1701  
1702      /**
1703       * A CyclicBarrier that uses timed await and fails with
1704 <     * AssertionFailedErrors instead of throwing checked exceptions.
1704 >     * AssertionErrors instead of throwing checked exceptions.
1705       */
1706      public static class CheckedBarrier extends CyclicBarrier {
1707          public CheckedBarrier(int parties) { super(parties); }
# Line 1835 | Line 1710 | public class JSR166TestCase extends Test
1710              try {
1711                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1712              } catch (TimeoutException timedOut) {
1713 <                throw new AssertionFailedError("timed out");
1713 >                throw new AssertionError("timed out");
1714              } catch (Exception fail) {
1715 <                AssertionFailedError afe =
1841 <                    new AssertionFailedError("Unexpected exception: " + fail);
1842 <                afe.initCause(fail);
1843 <                throw afe;
1715 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1716              }
1717          }
1718      }
# Line 1851 | Line 1723 | public class JSR166TestCase extends Test
1723              assertEquals(0, q.size());
1724              assertNull(q.peek());
1725              assertNull(q.poll());
1726 <            assertNull(q.poll(0, MILLISECONDS));
1726 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1727              assertEquals(q.toString(), "[]");
1728              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1729              assertFalse(q.iterator().hasNext());
# Line 1963 | Line 1835 | public class JSR166TestCase extends Test
1835              try { throwingAction.run(); }
1836              catch (Throwable t) {
1837                  threw = true;
1838 <                if (!expectedExceptionClass.isInstance(t)) {
1839 <                    AssertionFailedError afe =
1840 <                        new AssertionFailedError
1841 <                        ("Expected " + expectedExceptionClass.getName() +
1842 <                         ", got " + t.getClass().getName());
1971 <                    afe.initCause(t);
1972 <                    threadUnexpectedException(afe);
1973 <                }
1838 >                if (!expectedExceptionClass.isInstance(t))
1839 >                    throw new AssertionError(
1840 >                            "Expected " + expectedExceptionClass.getName() +
1841 >                            ", got " + t.getClass().getName(),
1842 >                            t);
1843              }
1844              if (!threw)
1845                  shouldThrow(expectedExceptionClass.getName());
# Line 2002 | Line 1871 | public class JSR166TestCase extends Test
1871      static <T> void shuffle(T[] array) {
1872          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1873      }
1874 +
1875 +    /**
1876 +     * Returns the same String as would be returned by {@link
1877 +     * Object#toString}, whether or not the given object's class
1878 +     * overrides toString().
1879 +     *
1880 +     * @see System#identityHashCode
1881 +     */
1882 +    static String identityString(Object x) {
1883 +        return x.getClass().getName()
1884 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1885 +    }
1886 +
1887 +    // --- Shared assertions for Executor tests ---
1888 +
1889 +    /**
1890 +     * Returns maximum number of tasks that can be submitted to given
1891 +     * pool (with bounded queue) before saturation (when submission
1892 +     * throws RejectedExecutionException).
1893 +     */
1894 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1895 +        BlockingQueue<Runnable> q = pool.getQueue();
1896 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1897 +    }
1898 +
1899 +    @SuppressWarnings("FutureReturnValueIgnored")
1900 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1901 +        try {
1902 +            e.execute((Runnable) null);
1903 +            shouldThrow();
1904 +        } catch (NullPointerException success) {}
1905 +
1906 +        if (! (e instanceof ExecutorService)) return;
1907 +        ExecutorService es = (ExecutorService) e;
1908 +        try {
1909 +            es.submit((Runnable) null);
1910 +            shouldThrow();
1911 +        } catch (NullPointerException success) {}
1912 +        try {
1913 +            es.submit((Runnable) null, Boolean.TRUE);
1914 +            shouldThrow();
1915 +        } catch (NullPointerException success) {}
1916 +        try {
1917 +            es.submit((Callable) null);
1918 +            shouldThrow();
1919 +        } catch (NullPointerException success) {}
1920 +
1921 +        if (! (e instanceof ScheduledExecutorService)) return;
1922 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1923 +        try {
1924 +            ses.schedule((Runnable) null,
1925 +                         randomTimeout(), randomTimeUnit());
1926 +            shouldThrow();
1927 +        } catch (NullPointerException success) {}
1928 +        try {
1929 +            ses.schedule((Callable) null,
1930 +                         randomTimeout(), randomTimeUnit());
1931 +            shouldThrow();
1932 +        } catch (NullPointerException success) {}
1933 +        try {
1934 +            ses.scheduleAtFixedRate((Runnable) null,
1935 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1936 +            shouldThrow();
1937 +        } catch (NullPointerException success) {}
1938 +        try {
1939 +            ses.scheduleWithFixedDelay((Runnable) null,
1940 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1941 +            shouldThrow();
1942 +        } catch (NullPointerException success) {}
1943 +    }
1944 +
1945 +    void setRejectedExecutionHandler(
1946 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1947 +        p.setRejectedExecutionHandler(handler);
1948 +        assertSame(handler, p.getRejectedExecutionHandler());
1949 +    }
1950 +
1951 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1952 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1953 +        final long savedTaskCount = p.getTaskCount();
1954 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1955 +        final int savedQueueSize = p.getQueue().size();
1956 +        final boolean stock = (p.getClass().getClassLoader() == null);
1957 +
1958 +        Runnable r = () -> {};
1959 +        Callable<Boolean> c = () -> Boolean.TRUE;
1960 +
1961 +        class Recorder implements RejectedExecutionHandler {
1962 +            public volatile Runnable r = null;
1963 +            public volatile ThreadPoolExecutor p = null;
1964 +            public void reset() { r = null; p = null; }
1965 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1966 +                assertNull(this.r);
1967 +                assertNull(this.p);
1968 +                this.r = r;
1969 +                this.p = p;
1970 +            }
1971 +        }
1972 +
1973 +        // check custom handler is invoked exactly once per task
1974 +        Recorder recorder = new Recorder();
1975 +        setRejectedExecutionHandler(p, recorder);
1976 +        for (int i = 2; i--> 0; ) {
1977 +            recorder.reset();
1978 +            p.execute(r);
1979 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
1980 +                assertSame(r, recorder.r);
1981 +            assertSame(p, recorder.p);
1982 +
1983 +            recorder.reset();
1984 +            assertFalse(p.submit(r).isDone());
1985 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1986 +            assertSame(p, recorder.p);
1987 +
1988 +            recorder.reset();
1989 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
1990 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1991 +            assertSame(p, recorder.p);
1992 +
1993 +            recorder.reset();
1994 +            assertFalse(p.submit(c).isDone());
1995 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1996 +            assertSame(p, recorder.p);
1997 +
1998 +            if (p instanceof ScheduledExecutorService) {
1999 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2000 +                ScheduledFuture<?> future;
2001 +
2002 +                recorder.reset();
2003 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2004 +                assertFalse(future.isDone());
2005 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2006 +                assertSame(p, recorder.p);
2007 +
2008 +                recorder.reset();
2009 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2010 +                assertFalse(future.isDone());
2011 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2012 +                assertSame(p, recorder.p);
2013 +
2014 +                recorder.reset();
2015 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2016 +                assertFalse(future.isDone());
2017 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2018 +                assertSame(p, recorder.p);
2019 +
2020 +                recorder.reset();
2021 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2022 +                assertFalse(future.isDone());
2023 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2024 +                assertSame(p, recorder.p);
2025 +            }
2026 +        }
2027 +
2028 +        // Checking our custom handler above should be sufficient, but
2029 +        // we add some integration tests of standard handlers.
2030 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2031 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2032 +
2033 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2034 +        try {
2035 +            p.execute(setThread);
2036 +            shouldThrow();
2037 +        } catch (RejectedExecutionException success) {}
2038 +        assertNull(thread.get());
2039 +
2040 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2041 +        p.execute(setThread);
2042 +        assertNull(thread.get());
2043 +
2044 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2045 +        p.execute(setThread);
2046 +        if (p.isShutdown())
2047 +            assertNull(thread.get());
2048 +        else
2049 +            assertSame(Thread.currentThread(), thread.get());
2050 +
2051 +        setRejectedExecutionHandler(p, savedHandler);
2052 +
2053 +        // check that pool was not perturbed by handlers
2054 +        assertEquals(savedTaskCount, p.getTaskCount());
2055 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2056 +        assertEquals(savedQueueSize, p.getQueue().size());
2057 +    }
2058 +
2059 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2060 +        assertEquals(x, y);
2061 +        assertEquals(y, x);
2062 +        assertEquals(x.isEmpty(), y.isEmpty());
2063 +        assertEquals(x.size(), y.size());
2064 +        if (x instanceof List) {
2065 +            assertEquals(x.toString(), y.toString());
2066 +        }
2067 +        if (x instanceof List || x instanceof Set) {
2068 +            assertEquals(x.hashCode(), y.hashCode());
2069 +        }
2070 +        if (x instanceof List || x instanceof Deque) {
2071 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2072 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2073 +                                     y.toArray(new Object[0])));
2074 +        }
2075 +    }
2076 +
2077 +    /**
2078 +     * A weaker form of assertCollectionsEquals which does not insist
2079 +     * that the two collections satisfy Object#equals(Object), since
2080 +     * they may use identity semantics as Deques do.
2081 +     */
2082 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2083 +        if (x instanceof List || x instanceof Set)
2084 +            assertCollectionsEquals(x, y);
2085 +        else {
2086 +            assertEquals(x.isEmpty(), y.isEmpty());
2087 +            assertEquals(x.size(), y.size());
2088 +            assertEquals(new HashSet(x), new HashSet(y));
2089 +            if (x instanceof Deque) {
2090 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2091 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2092 +                                         y.toArray(new Object[0])));
2093 +            }
2094 +        }
2095 +    }
2096   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines