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.204 by jsr166, Sat Oct 15 18:51:12 2016 UTC vs.
Revision 1.238 by jsr166, Mon Dec 11 00:27:08 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
# 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
17 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
18 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -Djava.util.secureRandomSeed=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 30 | 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;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 41 | Line 63 | import java.security.ProtectionDomain;
63   import java.security.SecurityPermission;
64   import java.util.ArrayList;
65   import java.util.Arrays;
66 + import java.util.Collection;
67   import java.util.Collections;
68   import java.util.Date;
69   import java.util.Enumeration;
# Line 53 | 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;
71 import java.util.regex.Matcher;
100   import java.util.regex.Pattern;
101  
102   import junit.framework.AssertionFailedError;
# Line 278 | Line 306 | public class JSR166TestCase extends Test
306  
307   //     public static String cpuModel() {
308   //         try {
309 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
309 > //             java.util.regex.Matcher matcher
310 > //               = Pattern.compile("model name\\s*: (.*)")
311   //                 .matcher(new String(
312 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
312 > //                     java.nio.file.Files.readAllBytes(
313 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
314   //             matcher.find();
315   //             return matcher.group(1);
316   //         } catch (Exception ex) { return null; }
# Line 415 | Line 445 | public class JSR166TestCase extends Test
445          }
446      }
447  
448 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
449 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
450 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
451 <    public static boolean atLeastJava9() {
452 <        return JAVA_CLASS_VERSION >= 53.0
423 <            // As of 2015-09, java9 still uses 52.0 class file version
424 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
425 <    }
426 <    public static boolean atLeastJava10() {
427 <        return JAVA_CLASS_VERSION >= 54.0
428 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
429 <    }
448 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
449 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
450 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
451 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
452 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
453  
454      /**
455       * Collects all JSR166 unit tests as one suite.
# Line 447 | Line 470 | public class JSR166TestCase extends Test
470              AbstractQueuedLongSynchronizerTest.suite(),
471              ArrayBlockingQueueTest.suite(),
472              ArrayDequeTest.suite(),
473 +            ArrayListTest.suite(),
474              AtomicBooleanTest.suite(),
475              AtomicIntegerArrayTest.suite(),
476              AtomicIntegerFieldUpdaterTest.suite(),
# Line 498 | Line 522 | public class JSR166TestCase extends Test
522              TreeMapTest.suite(),
523              TreeSetTest.suite(),
524              TreeSubMapTest.suite(),
525 <            TreeSubSetTest.suite());
525 >            TreeSubSetTest.suite(),
526 >            VectorTest.suite());
527  
528          // Java8+ test classes
529          if (atLeastJava8()) {
530              String[] java8TestClassNames = {
531 +                "ArrayDeque8Test",
532                  "Atomic8Test",
533                  "CompletableFutureTest",
534                  "ConcurrentHashMap8Test",
# Line 511 | Line 537 | public class JSR166TestCase extends Test
537                  "DoubleAdderTest",
538                  "ForkJoinPool8Test",
539                  "ForkJoinTask8Test",
540 +                "HashMapTest",
541 +                "LinkedBlockingDeque8Test",
542 +                "LinkedBlockingQueue8Test",
543                  "LongAccumulatorTest",
544                  "LongAdderTest",
545                  "SplittableRandomTest",
# Line 533 | Line 562 | public class JSR166TestCase extends Test
562                  "AtomicReference9Test",
563                  "AtomicReferenceArray9Test",
564                  "ExecutorCompletionService9Test",
565 +                "ForkJoinPool9Test",
566              };
567              addNamedTestClasses(suite, java9TestClassNames);
568          }
# Line 543 | Line 573 | public class JSR166TestCase extends Test
573      /** Returns list of junit-style test method names in given class. */
574      public static ArrayList<String> testMethodNames(Class<?> testClass) {
575          Method[] methods = testClass.getDeclaredMethods();
576 <        ArrayList<String> names = new ArrayList<String>(methods.length);
576 >        ArrayList<String> names = new ArrayList<>(methods.length);
577          for (Method method : methods) {
578              if (method.getName().startsWith("test")
579                  && Modifier.isPublic(method.getModifiers())
# Line 608 | Line 638 | public class JSR166TestCase extends Test
638      public static long MEDIUM_DELAY_MS;
639      public static long LONG_DELAY_MS;
640  
641 +    private static final long RANDOM_TIMEOUT;
642 +    private static final long RANDOM_EXPIRED_TIMEOUT;
643 +    private static final TimeUnit RANDOM_TIMEUNIT;
644 +    static {
645 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
646 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
647 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
648 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
649 +        TimeUnit[] timeUnits = TimeUnit.values();
650 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
651 +    }
652 +
653 +    /**
654 +     * Returns a timeout for use when any value at all will do.
655 +     */
656 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
657 +
658 +    /**
659 +     * Returns a timeout that means "no waiting", i.e. not positive.
660 +     */
661 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
662 +
663 +    /**
664 +     * Returns a random non-null TimeUnit.
665 +     */
666 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
667 +
668      /**
669       * Returns the shortest timed delay. This can be scaled up for
670       * slow machines using the jsr166.delay.factor system property,
# Line 628 | Line 685 | public class JSR166TestCase extends Test
685          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
686      }
687  
688 +    private static final long TIMEOUT_DELAY_MS
689 +        = (long) (12.0 * Math.cbrt(delayFactor));
690 +
691      /**
692 <     * Returns a timeout in milliseconds to be used in tests that
693 <     * verify that operations block or time out.
692 >     * Returns a timeout in milliseconds to be used in tests that verify
693 >     * that operations block or time out.  We want this to be longer
694 >     * than the OS scheduling quantum, but not too long, so don't scale
695 >     * linearly with delayFactor; we use "crazy" cube root instead.
696       */
697 <    long timeoutMillis() {
698 <        return SHORT_DELAY_MS / 4;
697 >    static long timeoutMillis() {
698 >        return TIMEOUT_DELAY_MS;
699      }
700  
701      /**
# Line 649 | Line 711 | public class JSR166TestCase extends Test
711       * The first exception encountered if any threadAssertXXX method fails.
712       */
713      private final AtomicReference<Throwable> threadFailure
714 <        = new AtomicReference<Throwable>(null);
714 >        = new AtomicReference<>(null);
715  
716      /**
717       * Records an exception so that it can be rethrown later in the test
# Line 1028 | Line 1090 | public class JSR166TestCase extends Test
1090      }
1091  
1092      /**
1093 <     * Checks that thread does not terminate within the default
1032 <     * millisecond delay of {@code timeoutMillis()}.
1033 <     */
1034 <    void assertThreadStaysAlive(Thread thread) {
1035 <        assertThreadStaysAlive(thread, timeoutMillis());
1036 <    }
1037 <
1038 <    /**
1039 <     * Checks that thread does not terminate within the given millisecond delay.
1040 <     */
1041 <    void assertThreadStaysAlive(Thread thread, long millis) {
1042 <        try {
1043 <            // No need to optimize the failing case via Thread.join.
1044 <            delay(millis);
1045 <            assertTrue(thread.isAlive());
1046 <        } catch (InterruptedException fail) {
1047 <            threadFail("Unexpected InterruptedException");
1048 <        }
1049 <    }
1050 <
1051 <    /**
1052 <     * Checks that the threads do not terminate within the default
1053 <     * millisecond delay of {@code timeoutMillis()}.
1093 >     * Checks that thread eventually enters the expected blocked thread state.
1094       */
1095 <    void assertThreadsStayAlive(Thread... threads) {
1096 <        assertThreadsStayAlive(timeoutMillis(), threads);
1097 <    }
1098 <
1099 <    /**
1100 <     * Checks that the threads do not terminate within the given millisecond delay.
1101 <     */
1102 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1103 <        try {
1104 <            // No need to optimize the failing case via Thread.join.
1105 <            delay(millis);
1106 <            for (Thread thread : threads)
1107 <                assertTrue(thread.isAlive());
1068 <        } catch (InterruptedException fail) {
1069 <            threadFail("Unexpected InterruptedException");
1095 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1096 >        // always sleep at least 1 ms, with high probability avoiding
1097 >        // transitory states
1098 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1099 >            try { delay(1); }
1100 >            catch (InterruptedException fail) {
1101 >                fail("Unexpected InterruptedException");
1102 >            }
1103 >            Thread.State s = thread.getState();
1104 >            if (s == expected)
1105 >                return;
1106 >            else if (s == Thread.State.TERMINATED)
1107 >                fail("Unexpected thread termination");
1108          }
1109 +        fail("timed out waiting for thread to enter thread state " + expected);
1110      }
1111  
1112      /**
# Line 1108 | Line 1147 | public class JSR166TestCase extends Test
1147      }
1148  
1149      /**
1150 +     * The maximum number of consecutive spurious wakeups we should
1151 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1152 +     */
1153 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1154 +
1155 +    /**
1156       * The number of elements to place in collections, arrays, etc.
1157       */
1158      public static final int SIZE = 20;
# Line 1211 | Line 1256 | public class JSR166TestCase extends Test
1256          }
1257          public void refresh() {}
1258          public String toString() {
1259 <            List<Permission> ps = new ArrayList<Permission>();
1259 >            List<Permission> ps = new ArrayList<>();
1260              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1261                  ps.add(e.nextElement());
1262              return "AdjustablePolicy with permissions " + ps;
# Line 1270 | Line 1315 | public class JSR166TestCase extends Test
1315                  startTime = System.nanoTime();
1316              else if (millisElapsedSince(startTime) > timeoutMillis) {
1317                  threadAssertTrue(thread.isAlive());
1318 <                return;
1318 >                fail("timed out waiting for thread to enter wait state");
1319 >            }
1320 >            Thread.yield();
1321 >        }
1322 >    }
1323 >
1324 >    /**
1325 >     * Spin-waits up to the specified number of milliseconds for the given
1326 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1327 >     * and additionally satisfy the given condition.
1328 >     */
1329 >    void waitForThreadToEnterWaitState(
1330 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1331 >        long startTime = 0L;
1332 >        for (;;) {
1333 >            Thread.State s = thread.getState();
1334 >            if (s == Thread.State.BLOCKED ||
1335 >                s == Thread.State.WAITING ||
1336 >                s == Thread.State.TIMED_WAITING) {
1337 >                try {
1338 >                    if (waitingForGodot.call())
1339 >                        return;
1340 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1341 >            }
1342 >            else if (s == Thread.State.TERMINATED)
1343 >                fail("Unexpected thread termination");
1344 >            else if (startTime == 0L)
1345 >                startTime = System.nanoTime();
1346 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1347 >                threadAssertTrue(thread.isAlive());
1348 >                fail("timed out waiting for thread to enter wait state");
1349              }
1350              Thread.yield();
1351          }
1352      }
1353  
1354      /**
1355 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1356 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1355 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1356 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1357       */
1358      void waitForThreadToEnterWaitState(Thread thread) {
1359          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1360      }
1361  
1362      /**
1363 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1364 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1365 +     * and additionally satisfy the given condition.
1366 +     */
1367 +    void waitForThreadToEnterWaitState(
1368 +        Thread thread, Callable<Boolean> waitingForGodot) {
1369 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1370 +    }
1371 +
1372 +    /**
1373       * Returns the number of milliseconds since time given by
1374       * startNanoTime, which must have been previously returned from a
1375       * call to {@link System#nanoTime()}.
# Line 1536 | Line 1621 | public class JSR166TestCase extends Test
1621          }
1622      }
1623  
1624 +    public void await(CyclicBarrier barrier) {
1625 +        try {
1626 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1627 +        } catch (Throwable fail) {
1628 +            threadUnexpectedException(fail);
1629 +        }
1630 +    }
1631 +
1632   //     /**
1633   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1634   //      */
# Line 1559 | Line 1652 | public class JSR166TestCase extends Test
1652          public String call() { throw new NullPointerException(); }
1653      }
1654  
1562    public static class CallableOne implements Callable<Integer> {
1563        public Integer call() { return one; }
1564    }
1565
1566    public class ShortRunnable extends CheckedRunnable {
1567        protected void realRun() throws Throwable {
1568            delay(SHORT_DELAY_MS);
1569        }
1570    }
1571
1572    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1573        protected void realRun() throws InterruptedException {
1574            delay(SHORT_DELAY_MS);
1575        }
1576    }
1577
1578    public class SmallRunnable extends CheckedRunnable {
1579        protected void realRun() throws Throwable {
1580            delay(SMALL_DELAY_MS);
1581        }
1582    }
1583
1655      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1656          protected void realRun() {
1657              try {
# Line 1589 | Line 1660 | public class JSR166TestCase extends Test
1660          }
1661      }
1662  
1592    public class SmallCallable extends CheckedCallable {
1593        protected Object realCall() throws InterruptedException {
1594            delay(SMALL_DELAY_MS);
1595            return Boolean.TRUE;
1596        }
1597    }
1598
1599    public class MediumRunnable extends CheckedRunnable {
1600        protected void realRun() throws Throwable {
1601            delay(MEDIUM_DELAY_MS);
1602        }
1603    }
1604
1605    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1606        protected void realRun() throws InterruptedException {
1607            delay(MEDIUM_DELAY_MS);
1608        }
1609    }
1610
1663      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1664          return new CheckedRunnable() {
1665              protected void realRun() {
# Line 1617 | Line 1669 | public class JSR166TestCase extends Test
1669              }};
1670      }
1671  
1620    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1621        protected void realRun() {
1622            try {
1623                delay(MEDIUM_DELAY_MS);
1624            } catch (InterruptedException ok) {}
1625        }
1626    }
1627
1628    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1629        protected void realRun() {
1630            try {
1631                delay(LONG_DELAY_MS);
1632            } catch (InterruptedException ok) {}
1633        }
1634    }
1635
1672      /**
1673       * For use as ThreadFactory in constructors
1674       */
# Line 1646 | Line 1682 | public class JSR166TestCase extends Test
1682          boolean isDone();
1683      }
1684  
1649    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1650        return new TrackedRunnable() {
1651                private volatile boolean done = false;
1652                public boolean isDone() { return done; }
1653                public void run() {
1654                    try {
1655                        delay(timeoutMillis);
1656                        done = true;
1657                    } catch (InterruptedException ok) {}
1658                }
1659            };
1660    }
1661
1662    public static class TrackedShortRunnable implements Runnable {
1663        public volatile boolean done = false;
1664        public void run() {
1665            try {
1666                delay(SHORT_DELAY_MS);
1667                done = true;
1668            } catch (InterruptedException ok) {}
1669        }
1670    }
1671
1672    public static class TrackedSmallRunnable implements Runnable {
1673        public volatile boolean done = false;
1674        public void run() {
1675            try {
1676                delay(SMALL_DELAY_MS);
1677                done = true;
1678            } catch (InterruptedException ok) {}
1679        }
1680    }
1681
1682    public static class TrackedMediumRunnable implements Runnable {
1683        public volatile boolean done = false;
1684        public void run() {
1685            try {
1686                delay(MEDIUM_DELAY_MS);
1687                done = true;
1688            } catch (InterruptedException ok) {}
1689        }
1690    }
1691
1692    public static class TrackedLongRunnable implements Runnable {
1693        public volatile boolean done = false;
1694        public void run() {
1695            try {
1696                delay(LONG_DELAY_MS);
1697                done = true;
1698            } catch (InterruptedException ok) {}
1699        }
1700    }
1701
1685      public static class TrackedNoOpRunnable implements Runnable {
1686          public volatile boolean done = false;
1687          public void run() {
# Line 1706 | Line 1689 | public class JSR166TestCase extends Test
1689          }
1690      }
1691  
1709    public static class TrackedCallable implements Callable {
1710        public volatile boolean done = false;
1711        public Object call() {
1712            try {
1713                delay(SMALL_DELAY_MS);
1714                done = true;
1715            } catch (InterruptedException ok) {}
1716            return Boolean.TRUE;
1717        }
1718    }
1719
1692      /**
1693       * Analog of CheckedRunnable for RecursiveAction
1694       */
# Line 1783 | Line 1755 | public class JSR166TestCase extends Test
1755              assertEquals(0, q.size());
1756              assertNull(q.peek());
1757              assertNull(q.poll());
1758 <            assertNull(q.poll(0, MILLISECONDS));
1758 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1759              assertEquals(q.toString(), "[]");
1760              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1761              assertFalse(q.iterator().hasNext());
# Line 1824 | Line 1796 | public class JSR166TestCase extends Test
1796          }
1797      }
1798  
1799 +    void assertImmutable(final Object o) {
1800 +        if (o instanceof Collection) {
1801 +            assertThrows(
1802 +                UnsupportedOperationException.class,
1803 +                new Runnable() { public void run() {
1804 +                        ((Collection) o).add(null);}});
1805 +        }
1806 +    }
1807 +
1808      @SuppressWarnings("unchecked")
1809      <T> T serialClone(T o) {
1810          try {
1811              ObjectInputStream ois = new ObjectInputStream
1812                  (new ByteArrayInputStream(serialBytes(o)));
1813              T clone = (T) ois.readObject();
1814 +            if (o == clone) assertImmutable(o);
1815              assertSame(o.getClass(), clone.getClass());
1816              return clone;
1817          } catch (Throwable fail) {
# Line 1838 | Line 1820 | public class JSR166TestCase extends Test
1820          }
1821      }
1822  
1823 +    /**
1824 +     * A version of serialClone that leaves error handling (for
1825 +     * e.g. NotSerializableException) up to the caller.
1826 +     */
1827 +    @SuppressWarnings("unchecked")
1828 +    <T> T serialClonePossiblyFailing(T o)
1829 +        throws ReflectiveOperationException, java.io.IOException {
1830 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1831 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1832 +        oos.writeObject(o);
1833 +        oos.flush();
1834 +        oos.close();
1835 +        ObjectInputStream ois = new ObjectInputStream
1836 +            (new ByteArrayInputStream(bos.toByteArray()));
1837 +        T clone = (T) ois.readObject();
1838 +        if (o == clone) assertImmutable(o);
1839 +        assertSame(o.getClass(), clone.getClass());
1840 +        return clone;
1841 +    }
1842 +
1843 +    /**
1844 +     * If o implements Cloneable and has a public clone method,
1845 +     * returns a clone of o, else null.
1846 +     */
1847 +    @SuppressWarnings("unchecked")
1848 +    <T> T cloneableClone(T o) {
1849 +        if (!(o instanceof Cloneable)) return null;
1850 +        final T clone;
1851 +        try {
1852 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1853 +        } catch (NoSuchMethodException ok) {
1854 +            return null;
1855 +        } catch (ReflectiveOperationException unexpected) {
1856 +            throw new Error(unexpected);
1857 +        }
1858 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1859 +        assertSame(o.getClass(), clone.getClass());
1860 +        return clone;
1861 +    }
1862 +
1863      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1864                               Runnable... throwingActions) {
1865          for (Runnable throwingAction : throwingActions) {
# Line 1884 | Line 1906 | public class JSR166TestCase extends Test
1906      static <T> void shuffle(T[] array) {
1907          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1908      }
1909 +
1910 +    /**
1911 +     * Returns the same String as would be returned by {@link
1912 +     * Object#toString}, whether or not the given object's class
1913 +     * overrides toString().
1914 +     *
1915 +     * @see System#identityHashCode
1916 +     */
1917 +    static String identityString(Object x) {
1918 +        return x.getClass().getName()
1919 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1920 +    }
1921 +
1922 +    // --- Shared assertions for Executor tests ---
1923 +
1924 +    /**
1925 +     * Returns maximum number of tasks that can be submitted to given
1926 +     * pool (with bounded queue) before saturation (when submission
1927 +     * throws RejectedExecutionException).
1928 +     */
1929 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1930 +        BlockingQueue<Runnable> q = pool.getQueue();
1931 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1932 +    }
1933 +
1934 +    @SuppressWarnings("FutureReturnValueIgnored")
1935 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1936 +        try {
1937 +            e.execute((Runnable) null);
1938 +            shouldThrow();
1939 +        } catch (NullPointerException success) {}
1940 +
1941 +        if (! (e instanceof ExecutorService)) return;
1942 +        ExecutorService es = (ExecutorService) e;
1943 +        try {
1944 +            es.submit((Runnable) null);
1945 +            shouldThrow();
1946 +        } catch (NullPointerException success) {}
1947 +        try {
1948 +            es.submit((Runnable) null, Boolean.TRUE);
1949 +            shouldThrow();
1950 +        } catch (NullPointerException success) {}
1951 +        try {
1952 +            es.submit((Callable) null);
1953 +            shouldThrow();
1954 +        } catch (NullPointerException success) {}
1955 +
1956 +        if (! (e instanceof ScheduledExecutorService)) return;
1957 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1958 +        try {
1959 +            ses.schedule((Runnable) null,
1960 +                         randomTimeout(), randomTimeUnit());
1961 +            shouldThrow();
1962 +        } catch (NullPointerException success) {}
1963 +        try {
1964 +            ses.schedule((Callable) null,
1965 +                         randomTimeout(), randomTimeUnit());
1966 +            shouldThrow();
1967 +        } catch (NullPointerException success) {}
1968 +        try {
1969 +            ses.scheduleAtFixedRate((Runnable) null,
1970 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1971 +            shouldThrow();
1972 +        } catch (NullPointerException success) {}
1973 +        try {
1974 +            ses.scheduleWithFixedDelay((Runnable) null,
1975 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1976 +            shouldThrow();
1977 +        } catch (NullPointerException success) {}
1978 +    }
1979 +
1980 +    void setRejectedExecutionHandler(
1981 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1982 +        p.setRejectedExecutionHandler(handler);
1983 +        assertSame(handler, p.getRejectedExecutionHandler());
1984 +    }
1985 +
1986 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1987 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1988 +        final long savedTaskCount = p.getTaskCount();
1989 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1990 +        final int savedQueueSize = p.getQueue().size();
1991 +        final boolean stock = (p.getClass().getClassLoader() == null);
1992 +
1993 +        Runnable r = () -> {};
1994 +        Callable<Boolean> c = () -> Boolean.TRUE;
1995 +
1996 +        class Recorder implements RejectedExecutionHandler {
1997 +            public volatile Runnable r = null;
1998 +            public volatile ThreadPoolExecutor p = null;
1999 +            public void reset() { r = null; p = null; }
2000 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2001 +                assertNull(this.r);
2002 +                assertNull(this.p);
2003 +                this.r = r;
2004 +                this.p = p;
2005 +            }
2006 +        }
2007 +
2008 +        // check custom handler is invoked exactly once per task
2009 +        Recorder recorder = new Recorder();
2010 +        setRejectedExecutionHandler(p, recorder);
2011 +        for (int i = 2; i--> 0; ) {
2012 +            recorder.reset();
2013 +            p.execute(r);
2014 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2015 +                assertSame(r, recorder.r);
2016 +            assertSame(p, recorder.p);
2017 +
2018 +            recorder.reset();
2019 +            assertFalse(p.submit(r).isDone());
2020 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2021 +            assertSame(p, recorder.p);
2022 +
2023 +            recorder.reset();
2024 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2025 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2026 +            assertSame(p, recorder.p);
2027 +
2028 +            recorder.reset();
2029 +            assertFalse(p.submit(c).isDone());
2030 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2031 +            assertSame(p, recorder.p);
2032 +
2033 +            if (p instanceof ScheduledExecutorService) {
2034 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2035 +                ScheduledFuture<?> future;
2036 +
2037 +                recorder.reset();
2038 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2039 +                assertFalse(future.isDone());
2040 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2041 +                assertSame(p, recorder.p);
2042 +
2043 +                recorder.reset();
2044 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2045 +                assertFalse(future.isDone());
2046 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2047 +                assertSame(p, recorder.p);
2048 +
2049 +                recorder.reset();
2050 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2051 +                assertFalse(future.isDone());
2052 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2053 +                assertSame(p, recorder.p);
2054 +
2055 +                recorder.reset();
2056 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2057 +                assertFalse(future.isDone());
2058 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2059 +                assertSame(p, recorder.p);
2060 +            }
2061 +        }
2062 +
2063 +        // Checking our custom handler above should be sufficient, but
2064 +        // we add some integration tests of standard handlers.
2065 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2066 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2067 +
2068 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2069 +        try {
2070 +            p.execute(setThread);
2071 +            shouldThrow();
2072 +        } catch (RejectedExecutionException success) {}
2073 +        assertNull(thread.get());
2074 +
2075 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2076 +        p.execute(setThread);
2077 +        assertNull(thread.get());
2078 +
2079 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2080 +        p.execute(setThread);
2081 +        if (p.isShutdown())
2082 +            assertNull(thread.get());
2083 +        else
2084 +            assertSame(Thread.currentThread(), thread.get());
2085 +
2086 +        setRejectedExecutionHandler(p, savedHandler);
2087 +
2088 +        // check that pool was not perturbed by handlers
2089 +        assertEquals(savedTaskCount, p.getTaskCount());
2090 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2091 +        assertEquals(savedQueueSize, p.getQueue().size());
2092 +    }
2093   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines