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.223 by jsr166, Sat May 13 19:13:09 2017 UTC vs.
Revision 1.242 by jsr166, Mon Feb 19 16:12:11 2018 UTC

# Line 76 | Line 76 | import java.util.concurrent.Callable;
76   import java.util.concurrent.CountDownLatch;
77   import java.util.concurrent.CyclicBarrier;
78   import java.util.concurrent.ExecutionException;
79 + import java.util.concurrent.Executor;
80   import java.util.concurrent.Executors;
81   import java.util.concurrent.ExecutorService;
82   import java.util.concurrent.ForkJoinPool;
83   import java.util.concurrent.Future;
84 + import java.util.concurrent.FutureTask;
85   import java.util.concurrent.RecursiveAction;
86   import java.util.concurrent.RecursiveTask;
87 + import java.util.concurrent.RejectedExecutionException;
88   import java.util.concurrent.RejectedExecutionHandler;
89   import java.util.concurrent.Semaphore;
90 + import java.util.concurrent.ScheduledExecutorService;
91 + import java.util.concurrent.ScheduledFuture;
92   import java.util.concurrent.SynchronousQueue;
93   import java.util.concurrent.ThreadFactory;
94   import java.util.concurrent.ThreadLocalRandom;
95   import java.util.concurrent.ThreadPoolExecutor;
96 + import java.util.concurrent.TimeUnit;
97   import java.util.concurrent.TimeoutException;
98   import java.util.concurrent.atomic.AtomicBoolean;
99   import java.util.concurrent.atomic.AtomicReference;
100   import java.util.regex.Pattern;
101  
96 import junit.framework.AssertionFailedError;
102   import junit.framework.Test;
103   import junit.framework.TestCase;
104   import junit.framework.TestResult;
# Line 413 | Line 418 | public class JSR166TestCase extends Test
418          for (String testClassName : testClassNames) {
419              try {
420                  Class<?> testClass = Class.forName(testClassName);
421 <                Method m = testClass.getDeclaredMethod("suite",
417 <                                                       new Class<?>[0]);
421 >                Method m = testClass.getDeclaredMethod("suite");
422                  suite.addTest(newTestSuite((Test)m.invoke(null)));
423 <            } catch (Exception e) {
424 <                throw new Error("Missing test class", e);
423 >            } catch (ReflectiveOperationException e) {
424 >                throw new AssertionError("Missing test class", e);
425              }
426          }
427      }
# Line 439 | Line 443 | public class JSR166TestCase extends Test
443          }
444      }
445  
446 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
447 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
448 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
449 <    public static boolean atLeastJava9() {
450 <        return JAVA_CLASS_VERSION >= 53.0
447 <            // As of 2015-09, java9 still uses 52.0 class file version
448 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
449 <    }
450 <    public static boolean atLeastJava10() {
451 <        return JAVA_CLASS_VERSION >= 54.0
452 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
453 <    }
446 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
447 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
448 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
449 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
450 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
451  
452      /**
453       * Collects all JSR166 unit tests as one suite.
# Line 538 | Line 535 | public class JSR166TestCase extends Test
535                  "DoubleAdderTest",
536                  "ForkJoinPool8Test",
537                  "ForkJoinTask8Test",
538 +                "HashMapTest",
539                  "LinkedBlockingDeque8Test",
540                  "LinkedBlockingQueue8Test",
541                  "LongAccumulatorTest",
# Line 600 | Line 598 | public class JSR166TestCase extends Test
598              for (String methodName : testMethodNames(testClass))
599                  suite.addTest((Test) c.newInstance(data, methodName));
600              return suite;
601 <        } catch (Exception e) {
602 <            throw new Error(e);
601 >        } catch (ReflectiveOperationException e) {
602 >            throw new AssertionError(e);
603          }
604      }
605  
# Line 617 | Line 615 | public class JSR166TestCase extends Test
615          if (atLeastJava8()) {
616              String name = testClass.getName();
617              String name8 = name.replaceAll("Test$", "8Test");
618 <            if (name.equals(name8)) throw new Error(name);
618 >            if (name.equals(name8)) throw new AssertionError(name);
619              try {
620                  return (Test)
621                      Class.forName(name8)
622 <                    .getMethod("testSuite", new Class[] { dataClass })
622 >                    .getMethod("testSuite", dataClass)
623                      .invoke(null, data);
624 <            } catch (Exception e) {
625 <                throw new Error(e);
624 >            } catch (ReflectiveOperationException e) {
625 >                throw new AssertionError(e);
626              }
627          } else {
628              return new TestSuite();
# Line 638 | Line 636 | public class JSR166TestCase extends Test
636      public static long MEDIUM_DELAY_MS;
637      public static long LONG_DELAY_MS;
638  
639 +    private static final long RANDOM_TIMEOUT;
640 +    private static final long RANDOM_EXPIRED_TIMEOUT;
641 +    private static final TimeUnit RANDOM_TIMEUNIT;
642 +    static {
643 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
644 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
645 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
646 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
647 +        TimeUnit[] timeUnits = TimeUnit.values();
648 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
649 +    }
650 +
651 +    /**
652 +     * Returns a timeout for use when any value at all will do.
653 +     */
654 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
655 +
656 +    /**
657 +     * Returns a timeout that means "no waiting", i.e. not positive.
658 +     */
659 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
660 +
661 +    /**
662 +     * Returns a random non-null TimeUnit.
663 +     */
664 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
665 +
666      /**
667       * Returns the shortest timed delay. This can be scaled up for
668       * slow machines using the jsr166.delay.factor system property,
# Line 706 | Line 731 | public class JSR166TestCase extends Test
731          String msg = toString() + ": " + String.format(format, args);
732          System.err.println(msg);
733          dumpTestThreads();
734 <        throw new AssertionFailedError(msg);
734 >        throw new AssertionError(msg);
735      }
736  
737      /**
# Line 727 | Line 752 | public class JSR166TestCase extends Test
752                  throw (RuntimeException) t;
753              else if (t instanceof Exception)
754                  throw (Exception) t;
755 <            else {
756 <                AssertionFailedError afe =
732 <                    new AssertionFailedError(t.toString());
733 <                afe.initCause(t);
734 <                throw afe;
735 <            }
755 >            else
756 >                throw new AssertionError(t.toString(), t);
757          }
758  
759          if (Thread.interrupted())
# Line 766 | Line 787 | public class JSR166TestCase extends Test
787  
788      /**
789       * Just like fail(reason), but additionally recording (using
790 <     * threadRecordFailure) any AssertionFailedError thrown, so that
791 <     * the current testcase will fail.
790 >     * threadRecordFailure) any AssertionError thrown, so that the
791 >     * current testcase will fail.
792       */
793      public void threadFail(String reason) {
794          try {
795              fail(reason);
796 <        } catch (AssertionFailedError t) {
797 <            threadRecordFailure(t);
798 <            throw t;
796 >        } catch (AssertionError fail) {
797 >            threadRecordFailure(fail);
798 >            throw fail;
799          }
800      }
801  
802      /**
803       * Just like assertTrue(b), but additionally recording (using
804 <     * threadRecordFailure) any AssertionFailedError thrown, so that
805 <     * the current testcase will fail.
804 >     * threadRecordFailure) any AssertionError thrown, so that the
805 >     * current testcase will fail.
806       */
807      public void threadAssertTrue(boolean b) {
808          try {
809              assertTrue(b);
810 <        } catch (AssertionFailedError t) {
811 <            threadRecordFailure(t);
812 <            throw t;
810 >        } catch (AssertionError fail) {
811 >            threadRecordFailure(fail);
812 >            throw fail;
813          }
814      }
815  
816      /**
817       * Just like assertFalse(b), but additionally recording (using
818 <     * threadRecordFailure) any AssertionFailedError thrown, so that
819 <     * the current testcase will fail.
818 >     * threadRecordFailure) any AssertionError thrown, so that the
819 >     * current testcase will fail.
820       */
821      public void threadAssertFalse(boolean b) {
822          try {
823              assertFalse(b);
824 <        } catch (AssertionFailedError t) {
825 <            threadRecordFailure(t);
826 <            throw t;
824 >        } catch (AssertionError fail) {
825 >            threadRecordFailure(fail);
826 >            throw fail;
827          }
828      }
829  
830      /**
831       * Just like assertNull(x), but additionally recording (using
832 <     * threadRecordFailure) any AssertionFailedError thrown, so that
833 <     * the current testcase will fail.
832 >     * threadRecordFailure) any AssertionError thrown, so that the
833 >     * current testcase will fail.
834       */
835      public void threadAssertNull(Object x) {
836          try {
837              assertNull(x);
838 <        } catch (AssertionFailedError t) {
839 <            threadRecordFailure(t);
840 <            throw t;
838 >        } catch (AssertionError fail) {
839 >            threadRecordFailure(fail);
840 >            throw fail;
841          }
842      }
843  
844      /**
845       * Just like assertEquals(x, y), but additionally recording (using
846 <     * threadRecordFailure) any AssertionFailedError thrown, so that
847 <     * the current testcase will fail.
846 >     * threadRecordFailure) any AssertionError thrown, so that the
847 >     * current testcase will fail.
848       */
849      public void threadAssertEquals(long x, long y) {
850          try {
851              assertEquals(x, y);
852 <        } catch (AssertionFailedError t) {
853 <            threadRecordFailure(t);
854 <            throw t;
852 >        } catch (AssertionError fail) {
853 >            threadRecordFailure(fail);
854 >            throw fail;
855          }
856      }
857  
858      /**
859       * Just like assertEquals(x, y), but additionally recording (using
860 <     * threadRecordFailure) any AssertionFailedError thrown, so that
861 <     * the current testcase will fail.
860 >     * threadRecordFailure) any AssertionError thrown, so that the
861 >     * current testcase will fail.
862       */
863      public void threadAssertEquals(Object x, Object y) {
864          try {
865              assertEquals(x, y);
866 <        } catch (AssertionFailedError fail) {
866 >        } catch (AssertionError fail) {
867              threadRecordFailure(fail);
868              throw fail;
869          } catch (Throwable fail) {
# Line 852 | Line 873 | public class JSR166TestCase extends Test
873  
874      /**
875       * Just like assertSame(x, y), but additionally recording (using
876 <     * threadRecordFailure) any AssertionFailedError thrown, so that
877 <     * the current testcase will fail.
876 >     * threadRecordFailure) any AssertionError thrown, so that the
877 >     * current testcase will fail.
878       */
879      public void threadAssertSame(Object x, Object y) {
880          try {
881              assertSame(x, y);
882 <        } catch (AssertionFailedError fail) {
882 >        } catch (AssertionError fail) {
883              threadRecordFailure(fail);
884              throw fail;
885          }
# Line 880 | Line 901 | public class JSR166TestCase extends Test
901  
902      /**
903       * Records the given exception using {@link #threadRecordFailure},
904 <     * then rethrows the exception, wrapping it in an
905 <     * AssertionFailedError if necessary.
904 >     * then rethrows the exception, wrapping it in an AssertionError
905 >     * if necessary.
906       */
907      public void threadUnexpectedException(Throwable t) {
908          threadRecordFailure(t);
# Line 890 | Line 911 | public class JSR166TestCase extends Test
911              throw (RuntimeException) t;
912          else if (t instanceof Error)
913              throw (Error) t;
914 <        else {
915 <            AssertionFailedError afe =
895 <                new AssertionFailedError("unexpected exception: " + t);
896 <            afe.initCause(t);
897 <            throw afe;
898 <        }
914 >        else
915 >            throw new AssertionError("unexpected exception: " + t, t);
916      }
917  
918      /**
# Line 1063 | Line 1080 | public class JSR166TestCase extends Test
1080      }
1081  
1082      /**
1083 <     * Checks that thread does not terminate within the default
1067 <     * millisecond delay of {@code timeoutMillis()}.
1068 <     */
1069 <    void assertThreadStaysAlive(Thread thread) {
1070 <        assertThreadStaysAlive(thread, timeoutMillis());
1071 <    }
1072 <
1073 <    /**
1074 <     * Checks that thread does not terminate within the given millisecond delay.
1083 >     * Checks that thread eventually enters the expected blocked thread state.
1084       */
1085 <    void assertThreadStaysAlive(Thread thread, long millis) {
1086 <        try {
1087 <            // No need to optimize the failing case via Thread.join.
1088 <            delay(millis);
1089 <            assertTrue(thread.isAlive());
1090 <        } catch (InterruptedException fail) {
1091 <            threadFail("Unexpected InterruptedException");
1092 <        }
1093 <    }
1094 <
1095 <    /**
1096 <     * Checks that the threads do not terminate within the default
1097 <     * millisecond delay of {@code timeoutMillis()}.
1089 <     */
1090 <    void assertThreadsStayAlive(Thread... threads) {
1091 <        assertThreadsStayAlive(timeoutMillis(), threads);
1092 <    }
1093 <
1094 <    /**
1095 <     * Checks that the threads do not terminate within the given millisecond delay.
1096 <     */
1097 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1098 <        try {
1099 <            // No need to optimize the failing case via Thread.join.
1100 <            delay(millis);
1101 <            for (Thread thread : threads)
1102 <                assertTrue(thread.isAlive());
1103 <        } catch (InterruptedException fail) {
1104 <            threadFail("Unexpected InterruptedException");
1085 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1086 >        // always sleep at least 1 ms, with high probability avoiding
1087 >        // transitory states
1088 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1089 >            try { delay(1); }
1090 >            catch (InterruptedException fail) {
1091 >                throw new AssertionError("Unexpected InterruptedException", fail);
1092 >            }
1093 >            Thread.State s = thread.getState();
1094 >            if (s == expected)
1095 >                return;
1096 >            else if (s == Thread.State.TERMINATED)
1097 >                fail("Unexpected thread termination");
1098          }
1099 +        fail("timed out waiting for thread to enter thread state " + expected);
1100      }
1101  
1102      /**
# Line 1280 | Line 1274 | public class JSR166TestCase extends Test
1274  
1275      /**
1276       * Sleeps until the given time has elapsed.
1277 <     * Throws AssertionFailedError if interrupted.
1277 >     * Throws AssertionError if interrupted.
1278       */
1279      static void sleep(long millis) {
1280          try {
1281              delay(millis);
1282          } catch (InterruptedException fail) {
1283 <            AssertionFailedError afe =
1290 <                new AssertionFailedError("Unexpected InterruptedException");
1291 <            afe.initCause(fail);
1292 <            throw afe;
1283 >            throw new AssertionError("Unexpected InterruptedException", fail);
1284          }
1285      }
1286  
# Line 1380 | Line 1371 | public class JSR166TestCase extends Test
1371   //             r.run();
1372   //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1373   //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1374 < //             throw new AssertionFailedError("did not return promptly");
1374 > //             throw new AssertionError("did not return promptly");
1375   //     }
1376  
1377   //     void assertTerminatesPromptly(Runnable r) {
# Line 1397 | Line 1388 | public class JSR166TestCase extends Test
1388              assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1389          } catch (Throwable fail) { threadUnexpectedException(fail); }
1390          if (millisElapsedSince(startTime) > timeoutMillis/2)
1391 <            throw new AssertionFailedError("timed get did not return promptly");
1391 >            throw new AssertionError("timed get did not return promptly");
1392      }
1393  
1394      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1455 | Line 1446 | public class JSR166TestCase extends Test
1446          }
1447      }
1448  
1458    public abstract class RunnableShouldThrow implements Runnable {
1459        protected abstract void realRun() throws Throwable;
1460
1461        final Class<?> exceptionClass;
1462
1463        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1464            this.exceptionClass = exceptionClass;
1465        }
1466
1467        public final void run() {
1468            try {
1469                realRun();
1470                threadShouldThrow(exceptionClass.getSimpleName());
1471            } catch (Throwable t) {
1472                if (! exceptionClass.isInstance(t))
1473                    threadUnexpectedException(t);
1474            }
1475        }
1476    }
1477
1449      public abstract class ThreadShouldThrow extends Thread {
1450          protected abstract void realRun() throws Throwable;
1451  
# Line 1617 | Line 1588 | public class JSR166TestCase extends Test
1588          }
1589      }
1590  
1591 +    public void await(CyclicBarrier barrier) {
1592 +        try {
1593 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1594 +        } catch (Throwable fail) {
1595 +            threadUnexpectedException(fail);
1596 +        }
1597 +    }
1598 +
1599   //     /**
1600   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1601   //      */
# Line 1631 | Line 1610 | public class JSR166TestCase extends Test
1610   //         long startTime = System.nanoTime();
1611   //         while (!flag.get()) {
1612   //             if (millisElapsedSince(startTime) > timeoutMillis)
1613 < //                 throw new AssertionFailedError("timed out");
1613 > //                 throw new AssertionError("timed out");
1614   //             Thread.yield();
1615   //         }
1616   //     }
# Line 1640 | Line 1619 | public class JSR166TestCase extends Test
1619          public String call() { throw new NullPointerException(); }
1620      }
1621  
1643    public static class CallableOne implements Callable<Integer> {
1644        public Integer call() { return one; }
1645    }
1646
1647    public class ShortRunnable extends CheckedRunnable {
1648        protected void realRun() throws Throwable {
1649            delay(SHORT_DELAY_MS);
1650        }
1651    }
1652
1653    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1654        protected void realRun() throws InterruptedException {
1655            delay(SHORT_DELAY_MS);
1656        }
1657    }
1658
1659    public class SmallRunnable extends CheckedRunnable {
1660        protected void realRun() throws Throwable {
1661            delay(SMALL_DELAY_MS);
1662        }
1663    }
1664
1622      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1623          protected void realRun() {
1624              try {
# Line 1670 | Line 1627 | public class JSR166TestCase extends Test
1627          }
1628      }
1629  
1673    public class SmallCallable extends CheckedCallable {
1674        protected Object realCall() throws InterruptedException {
1675            delay(SMALL_DELAY_MS);
1676            return Boolean.TRUE;
1677        }
1678    }
1679
1680    public class MediumRunnable extends CheckedRunnable {
1681        protected void realRun() throws Throwable {
1682            delay(MEDIUM_DELAY_MS);
1683        }
1684    }
1685
1686    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1687        protected void realRun() throws InterruptedException {
1688            delay(MEDIUM_DELAY_MS);
1689        }
1690    }
1691
1630      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1631          return new CheckedRunnable() {
1632              protected void realRun() {
# Line 1698 | Line 1636 | public class JSR166TestCase extends Test
1636              }};
1637      }
1638  
1701    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1702        protected void realRun() {
1703            try {
1704                delay(MEDIUM_DELAY_MS);
1705            } catch (InterruptedException ok) {}
1706        }
1707    }
1708
1709    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1710        protected void realRun() {
1711            try {
1712                delay(LONG_DELAY_MS);
1713            } catch (InterruptedException ok) {}
1714        }
1715    }
1716
1639      /**
1640       * For use as ThreadFactory in constructors
1641       */
# Line 1727 | Line 1649 | public class JSR166TestCase extends Test
1649          boolean isDone();
1650      }
1651  
1730    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1731        return new TrackedRunnable() {
1732                private volatile boolean done = false;
1733                public boolean isDone() { return done; }
1734                public void run() {
1735                    try {
1736                        delay(timeoutMillis);
1737                        done = true;
1738                    } catch (InterruptedException ok) {}
1739                }
1740            };
1741    }
1742
1743    public static class TrackedShortRunnable implements Runnable {
1744        public volatile boolean done = false;
1745        public void run() {
1746            try {
1747                delay(SHORT_DELAY_MS);
1748                done = true;
1749            } catch (InterruptedException ok) {}
1750        }
1751    }
1752
1753    public static class TrackedSmallRunnable implements Runnable {
1754        public volatile boolean done = false;
1755        public void run() {
1756            try {
1757                delay(SMALL_DELAY_MS);
1758                done = true;
1759            } catch (InterruptedException ok) {}
1760        }
1761    }
1762
1763    public static class TrackedMediumRunnable implements Runnable {
1764        public volatile boolean done = false;
1765        public void run() {
1766            try {
1767                delay(MEDIUM_DELAY_MS);
1768                done = true;
1769            } catch (InterruptedException ok) {}
1770        }
1771    }
1772
1773    public static class TrackedLongRunnable implements Runnable {
1774        public volatile boolean done = false;
1775        public void run() {
1776            try {
1777                delay(LONG_DELAY_MS);
1778                done = true;
1779            } catch (InterruptedException ok) {}
1780        }
1781    }
1782
1652      public static class TrackedNoOpRunnable implements Runnable {
1653          public volatile boolean done = false;
1654          public void run() {
# Line 1787 | Line 1656 | public class JSR166TestCase extends Test
1656          }
1657      }
1658  
1790    public static class TrackedCallable implements Callable {
1791        public volatile boolean done = false;
1792        public Object call() {
1793            try {
1794                delay(SMALL_DELAY_MS);
1795                done = true;
1796            } catch (InterruptedException ok) {}
1797            return Boolean.TRUE;
1798        }
1799    }
1800
1659      /**
1660       * Analog of CheckedRunnable for RecursiveAction
1661       */
# Line 1839 | Line 1697 | public class JSR166TestCase extends Test
1697  
1698      /**
1699       * A CyclicBarrier that uses timed await and fails with
1700 <     * AssertionFailedErrors instead of throwing checked exceptions.
1700 >     * AssertionErrors instead of throwing checked exceptions.
1701       */
1702      public static class CheckedBarrier extends CyclicBarrier {
1703          public CheckedBarrier(int parties) { super(parties); }
# Line 1848 | Line 1706 | public class JSR166TestCase extends Test
1706              try {
1707                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1708              } catch (TimeoutException timedOut) {
1709 <                throw new AssertionFailedError("timed out");
1709 >                throw new AssertionError("timed out");
1710              } catch (Exception fail) {
1711 <                AssertionFailedError afe =
1854 <                    new AssertionFailedError("Unexpected exception: " + fail);
1855 <                afe.initCause(fail);
1856 <                throw afe;
1711 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1712              }
1713          }
1714      }
# Line 1864 | Line 1719 | public class JSR166TestCase extends Test
1719              assertEquals(0, q.size());
1720              assertNull(q.peek());
1721              assertNull(q.poll());
1722 <            assertNull(q.poll(0, MILLISECONDS));
1722 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1723              assertEquals(q.toString(), "[]");
1724              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1725              assertFalse(q.iterator().hasNext());
# Line 1976 | Line 1831 | public class JSR166TestCase extends Test
1831              try { throwingAction.run(); }
1832              catch (Throwable t) {
1833                  threw = true;
1834 <                if (!expectedExceptionClass.isInstance(t)) {
1835 <                    AssertionFailedError afe =
1836 <                        new AssertionFailedError
1837 <                        ("Expected " + expectedExceptionClass.getName() +
1838 <                         ", got " + t.getClass().getName());
1984 <                    afe.initCause(t);
1985 <                    threadUnexpectedException(afe);
1986 <                }
1834 >                if (!expectedExceptionClass.isInstance(t))
1835 >                    throw new AssertionError(
1836 >                            "Expected " + expectedExceptionClass.getName() +
1837 >                            ", got " + t.getClass().getName(),
1838 >                            t);
1839              }
1840              if (!threw)
1841                  shouldThrow(expectedExceptionClass.getName());
# Line 2015 | Line 1867 | public class JSR166TestCase extends Test
1867      static <T> void shuffle(T[] array) {
1868          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1869      }
1870 +
1871 +    /**
1872 +     * Returns the same String as would be returned by {@link
1873 +     * Object#toString}, whether or not the given object's class
1874 +     * overrides toString().
1875 +     *
1876 +     * @see System#identityHashCode
1877 +     */
1878 +    static String identityString(Object x) {
1879 +        return x.getClass().getName()
1880 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1881 +    }
1882 +
1883 +    // --- Shared assertions for Executor tests ---
1884 +
1885 +    /**
1886 +     * Returns maximum number of tasks that can be submitted to given
1887 +     * pool (with bounded queue) before saturation (when submission
1888 +     * throws RejectedExecutionException).
1889 +     */
1890 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1891 +        BlockingQueue<Runnable> q = pool.getQueue();
1892 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1893 +    }
1894 +
1895 +    @SuppressWarnings("FutureReturnValueIgnored")
1896 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1897 +        try {
1898 +            e.execute((Runnable) null);
1899 +            shouldThrow();
1900 +        } catch (NullPointerException success) {}
1901 +
1902 +        if (! (e instanceof ExecutorService)) return;
1903 +        ExecutorService es = (ExecutorService) e;
1904 +        try {
1905 +            es.submit((Runnable) null);
1906 +            shouldThrow();
1907 +        } catch (NullPointerException success) {}
1908 +        try {
1909 +            es.submit((Runnable) null, Boolean.TRUE);
1910 +            shouldThrow();
1911 +        } catch (NullPointerException success) {}
1912 +        try {
1913 +            es.submit((Callable) null);
1914 +            shouldThrow();
1915 +        } catch (NullPointerException success) {}
1916 +
1917 +        if (! (e instanceof ScheduledExecutorService)) return;
1918 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1919 +        try {
1920 +            ses.schedule((Runnable) null,
1921 +                         randomTimeout(), randomTimeUnit());
1922 +            shouldThrow();
1923 +        } catch (NullPointerException success) {}
1924 +        try {
1925 +            ses.schedule((Callable) null,
1926 +                         randomTimeout(), randomTimeUnit());
1927 +            shouldThrow();
1928 +        } catch (NullPointerException success) {}
1929 +        try {
1930 +            ses.scheduleAtFixedRate((Runnable) null,
1931 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1932 +            shouldThrow();
1933 +        } catch (NullPointerException success) {}
1934 +        try {
1935 +            ses.scheduleWithFixedDelay((Runnable) null,
1936 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1937 +            shouldThrow();
1938 +        } catch (NullPointerException success) {}
1939 +    }
1940 +
1941 +    void setRejectedExecutionHandler(
1942 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1943 +        p.setRejectedExecutionHandler(handler);
1944 +        assertSame(handler, p.getRejectedExecutionHandler());
1945 +    }
1946 +
1947 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1948 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1949 +        final long savedTaskCount = p.getTaskCount();
1950 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1951 +        final int savedQueueSize = p.getQueue().size();
1952 +        final boolean stock = (p.getClass().getClassLoader() == null);
1953 +
1954 +        Runnable r = () -> {};
1955 +        Callable<Boolean> c = () -> Boolean.TRUE;
1956 +
1957 +        class Recorder implements RejectedExecutionHandler {
1958 +            public volatile Runnable r = null;
1959 +            public volatile ThreadPoolExecutor p = null;
1960 +            public void reset() { r = null; p = null; }
1961 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1962 +                assertNull(this.r);
1963 +                assertNull(this.p);
1964 +                this.r = r;
1965 +                this.p = p;
1966 +            }
1967 +        }
1968 +
1969 +        // check custom handler is invoked exactly once per task
1970 +        Recorder recorder = new Recorder();
1971 +        setRejectedExecutionHandler(p, recorder);
1972 +        for (int i = 2; i--> 0; ) {
1973 +            recorder.reset();
1974 +            p.execute(r);
1975 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
1976 +                assertSame(r, recorder.r);
1977 +            assertSame(p, recorder.p);
1978 +
1979 +            recorder.reset();
1980 +            assertFalse(p.submit(r).isDone());
1981 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1982 +            assertSame(p, recorder.p);
1983 +
1984 +            recorder.reset();
1985 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
1986 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1987 +            assertSame(p, recorder.p);
1988 +
1989 +            recorder.reset();
1990 +            assertFalse(p.submit(c).isDone());
1991 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1992 +            assertSame(p, recorder.p);
1993 +
1994 +            if (p instanceof ScheduledExecutorService) {
1995 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
1996 +                ScheduledFuture<?> future;
1997 +
1998 +                recorder.reset();
1999 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2000 +                assertFalse(future.isDone());
2001 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2002 +                assertSame(p, recorder.p);
2003 +
2004 +                recorder.reset();
2005 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2006 +                assertFalse(future.isDone());
2007 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2008 +                assertSame(p, recorder.p);
2009 +
2010 +                recorder.reset();
2011 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2012 +                assertFalse(future.isDone());
2013 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2014 +                assertSame(p, recorder.p);
2015 +
2016 +                recorder.reset();
2017 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2018 +                assertFalse(future.isDone());
2019 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2020 +                assertSame(p, recorder.p);
2021 +            }
2022 +        }
2023 +
2024 +        // Checking our custom handler above should be sufficient, but
2025 +        // we add some integration tests of standard handlers.
2026 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2027 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2028 +
2029 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2030 +        try {
2031 +            p.execute(setThread);
2032 +            shouldThrow();
2033 +        } catch (RejectedExecutionException success) {}
2034 +        assertNull(thread.get());
2035 +
2036 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2037 +        p.execute(setThread);
2038 +        assertNull(thread.get());
2039 +
2040 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2041 +        p.execute(setThread);
2042 +        if (p.isShutdown())
2043 +            assertNull(thread.get());
2044 +        else
2045 +            assertSame(Thread.currentThread(), thread.get());
2046 +
2047 +        setRejectedExecutionHandler(p, savedHandler);
2048 +
2049 +        // check that pool was not perturbed by handlers
2050 +        assertEquals(savedTaskCount, p.getTaskCount());
2051 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2052 +        assertEquals(savedQueueSize, p.getQueue().size());
2053 +    }
2054   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines