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.66 by jsr166, Thu Oct 28 17:57:26 2010 UTC vs.
Revision 1.117 by jsr166, Mon Jun 9 18:17:37 2014 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
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10 + import java.io.ByteArrayInputStream;
11 + import java.io.ByteArrayOutputStream;
12 + import java.io.ObjectInputStream;
13 + import java.io.ObjectOutputStream;
14 + import java.lang.management.ManagementFactory;
15 + import java.lang.management.ThreadInfo;
16 + import java.lang.reflect.Method;
17 + import java.util.ArrayList;
18 + import java.util.Arrays;
19 + import java.util.Date;
20 + import java.util.Enumeration;
21 + import java.util.List;
22 + import java.util.NoSuchElementException;
23   import java.util.PropertyPermission;
24   import java.util.concurrent.*;
25 + import java.util.concurrent.atomic.AtomicBoolean;
26   import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28   import static java.util.concurrent.TimeUnit.NANOSECONDS;
29 + import java.util.regex.Pattern;
30   import java.security.CodeSource;
31   import java.security.Permission;
32   import java.security.PermissionCollection;
# Line 61 | Line 76 | import java.security.SecurityPermission;
76   *
77   * </ol>
78   *
79 < * <p> <b>Other notes</b>
79 > * <p><b>Other notes</b>
80   * <ul>
81   *
82   * <li> Usually, there is one testcase method per JSR166 method
# Line 114 | Line 129 | public class JSR166TestCase extends Test
129      private static final long profileThreshold =
130          Long.getLong("jsr166.profileThreshold", 100);
131  
132 +    /**
133 +     * The number of repetitions per test (for tickling rare bugs).
134 +     */
135 +    private static final int runsPerTest =
136 +        Integer.getInteger("jsr166.runsPerTest", 1);
137 +
138 +    /**
139 +     * A filter for tests to run, matching strings of the form
140 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
141 +     * Usefully combined with jsr166.runsPerTest.
142 +     */
143 +    private static final Pattern methodFilter = methodFilter();
144 +
145 +    private static Pattern methodFilter() {
146 +        String regex = System.getProperty("jsr166.methodFilter");
147 +        return (regex == null) ? null : Pattern.compile(regex);
148 +    }
149 +
150      protected void runTest() throws Throwable {
151 <        if (profileTests)
152 <            runTestProfiled();
153 <        else
154 <            super.runTest();
151 >        if (methodFilter == null
152 >            || methodFilter.matcher(toString()).find()) {
153 >            for (int i = 0; i < runsPerTest; i++) {
154 >                if (profileTests)
155 >                    runTestProfiled();
156 >                else
157 >                    super.runTest();
158 >            }
159 >        }
160      }
161  
162      protected void runTestProfiled() throws Throwable {
163 +        // Warmup run, notably to trigger all needed classloading.
164 +        super.runTest();
165          long t0 = System.nanoTime();
166          try {
167              super.runTest();
168          } finally {
169 <            long elapsedMillis =
130 <                (System.nanoTime() - t0) / (1000L * 1000L);
169 >            long elapsedMillis = millisElapsedSince(t0);
170              if (elapsedMillis >= profileThreshold)
171                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
172          }
173      }
174  
175      /**
176 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
176 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
177 >     * Optional command line arg provides the number of iterations to
178 >     * repeat running the tests.
179       */
180      public static void main(String[] args) {
181          if (useSecurityManager) {
# Line 166 | Line 207 | public class JSR166TestCase extends Test
207          return suite;
208      }
209  
210 +    public static void addNamedTestClasses(TestSuite suite,
211 +                                           String... testClassNames) {
212 +        for (String testClassName : testClassNames) {
213 +            try {
214 +                Class<?> testClass = Class.forName(testClassName);
215 +                Method m = testClass.getDeclaredMethod("suite",
216 +                                                       new Class<?>[0]);
217 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
218 +            } catch (Exception e) {
219 +                throw new Error("Missing test class", e);
220 +            }
221 +        }
222 +    }
223 +
224 +    public static final double JAVA_CLASS_VERSION;
225 +    public static final String JAVA_SPECIFICATION_VERSION;
226 +    static {
227 +        try {
228 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
229 +                new java.security.PrivilegedAction<Double>() {
230 +                public Double run() {
231 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
232 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
233 +                new java.security.PrivilegedAction<String>() {
234 +                public String run() {
235 +                    return System.getProperty("java.specification.version");}});
236 +        } catch (Throwable t) {
237 +            throw new Error(t);
238 +        }
239 +    }
240 +
241 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
242 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
243 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
244 +    public static boolean atLeastJava9() {
245 +        // As of 2014-05, java9 still uses 52.0 class file version
246 +        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
247 +    }
248 +
249      /**
250       * Collects all JSR166 unit tests as one suite.
251       */
252      public static Test suite() {
253 <        return newTestSuite(
253 >        // Java7+ test classes
254 >        TestSuite suite = newTestSuite(
255              ForkJoinPoolTest.suite(),
256              ForkJoinTaskTest.suite(),
257              RecursiveActionTest.suite(),
# Line 235 | Line 316 | public class JSR166TestCase extends Test
316              TreeSetTest.suite(),
317              TreeSubMapTest.suite(),
318              TreeSubSetTest.suite());
319 +
320 +        // Java8+ test classes
321 +        if (atLeastJava8()) {
322 +            String[] java8TestClassNames = {
323 +                "Atomic8Test",
324 +                "CompletableFutureTest",
325 +                "ConcurrentHashMap8Test",
326 +                "CountedCompleterTest",
327 +                "DoubleAccumulatorTest",
328 +                "DoubleAdderTest",
329 +                "ForkJoinPool8Test",
330 +                "ForkJoinTask8Test",
331 +                "LongAccumulatorTest",
332 +                "LongAdderTest",
333 +                "SplittableRandomTest",
334 +                "StampedLockTest",
335 +                "ThreadLocalRandom8Test",
336 +            };
337 +            addNamedTestClasses(suite, java8TestClassNames);
338 +        }
339 +
340 +        // Java9+ test classes
341 +        if (atLeastJava9()) {
342 +            String[] java9TestClassNames = {
343 +                "ThreadPoolExecutor9Test",
344 +            };
345 +            addNamedTestClasses(suite, java9TestClassNames);
346 +        }
347 +
348 +        return suite;
349      }
350  
351 +    // Delays for timing-dependent tests, in milliseconds.
352  
353      public static long SHORT_DELAY_MS;
354      public static long SMALL_DELAY_MS;
355      public static long MEDIUM_DELAY_MS;
356      public static long LONG_DELAY_MS;
357  
246
358      /**
359       * Returns the shortest timed delay. This could
360       * be reimplemented to use for example a Property.
# Line 252 | Line 363 | public class JSR166TestCase extends Test
363          return 50;
364      }
365  
255
366      /**
367       * Sets delays as multiples of SHORT_DELAY.
368       */
# Line 260 | Line 370 | public class JSR166TestCase extends Test
370          SHORT_DELAY_MS = getShortDelay();
371          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
372          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
373 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
373 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
374 >    }
375 >
376 >    /**
377 >     * Returns a timeout in milliseconds to be used in tests that
378 >     * verify that operations block or time out.
379 >     */
380 >    long timeoutMillis() {
381 >        return SHORT_DELAY_MS / 4;
382 >    }
383 >
384 >    /**
385 >     * Returns a new Date instance representing a time delayMillis
386 >     * milliseconds in the future.
387 >     */
388 >    Date delayedDate(long delayMillis) {
389 >        return new Date(System.currentTimeMillis() + delayMillis);
390      }
391  
392      /**
# Line 284 | Line 410 | public class JSR166TestCase extends Test
410      }
411  
412      /**
413 +     * Extra checks that get done for all test cases.
414 +     *
415       * Triggers test case failure if any thread assertions have failed,
416       * by rethrowing, in the test harness thread, any exception recorded
417       * earlier by threadRecordFailure.
418 +     *
419 +     * Triggers test case failure if interrupt status is set in the main thread.
420       */
421      public void tearDown() throws Exception {
422 <        Throwable t = threadFailure.get();
422 >        Throwable t = threadFailure.getAndSet(null);
423          if (t != null) {
424              if (t instanceof Error)
425                  throw (Error) t;
# Line 304 | Line 434 | public class JSR166TestCase extends Test
434                  throw afe;
435              }
436          }
437 +
438 +        if (Thread.interrupted())
439 +            throw new AssertionFailedError("interrupt status set in main thread");
440 +
441 +        checkForkJoinPoolThreadLeaks();
442 +    }
443 +
444 +    /**
445 +     * Find missing try { ... } finally { joinPool(e); }
446 +     */
447 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
448 +        Thread[] survivors = new Thread[5];
449 +        int count = Thread.enumerate(survivors);
450 +        for (int i = 0; i < count; i++) {
451 +            Thread thread = survivors[i];
452 +            String name = thread.getName();
453 +            if (name.startsWith("ForkJoinPool-")) {
454 +                // give thread some time to terminate
455 +                thread.join(LONG_DELAY_MS);
456 +                if (!thread.isAlive()) continue;
457 +                thread.stop();
458 +                throw new AssertionFailedError
459 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
460 +                                   toString(), name));
461 +            }
462 +        }
463      }
464  
465      /**
# Line 435 | Line 591 | public class JSR166TestCase extends Test
591          else {
592              AssertionFailedError afe =
593                  new AssertionFailedError("unexpected exception: " + t);
594 <            t.initCause(t);
594 >            afe.initCause(t);
595              throw afe;
596          }
597      }
598  
599      /**
600 +     * Delays, via Thread.sleep, for the given millisecond delay, but
601 +     * if the sleep is shorter than specified, may re-sleep or yield
602 +     * until time elapses.
603 +     */
604 +    static void delay(long millis) throws InterruptedException {
605 +        long startTime = System.nanoTime();
606 +        long ns = millis * 1000 * 1000;
607 +        for (;;) {
608 +            if (millis > 0L)
609 +                Thread.sleep(millis);
610 +            else // too short to sleep
611 +                Thread.yield();
612 +            long d = ns - (System.nanoTime() - startTime);
613 +            if (d > 0L)
614 +                millis = d / (1000 * 1000);
615 +            else
616 +                break;
617 +        }
618 +    }
619 +
620 +    /**
621       * Waits out termination of a thread pool or fails doing so.
622       */
623 <    public void joinPool(ExecutorService exec) {
623 >    void joinPool(ExecutorService exec) {
624          try {
625              exec.shutdown();
626              assertTrue("ExecutorService did not terminate in a timely manner",
627 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
627 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
628          } catch (SecurityException ok) {
629              // Allowed in case test doesn't have privs
630          } catch (InterruptedException ie) {
# Line 455 | Line 632 | public class JSR166TestCase extends Test
632          }
633      }
634  
635 +    /**
636 +     * A debugging tool to print all stack traces, as jstack does.
637 +     */
638 +    static void printAllStackTraces() {
639 +        for (ThreadInfo info :
640 +                 ManagementFactory.getThreadMXBean()
641 +                 .dumpAllThreads(true, true))
642 +            System.err.print(info);
643 +    }
644 +
645 +    /**
646 +     * Checks that thread does not terminate within the default
647 +     * millisecond delay of {@code timeoutMillis()}.
648 +     */
649 +    void assertThreadStaysAlive(Thread thread) {
650 +        assertThreadStaysAlive(thread, timeoutMillis());
651 +    }
652 +
653 +    /**
654 +     * Checks that thread does not terminate within the given millisecond delay.
655 +     */
656 +    void assertThreadStaysAlive(Thread thread, long millis) {
657 +        try {
658 +            // No need to optimize the failing case via Thread.join.
659 +            delay(millis);
660 +            assertTrue(thread.isAlive());
661 +        } catch (InterruptedException ie) {
662 +            fail("Unexpected InterruptedException");
663 +        }
664 +    }
665 +
666 +    /**
667 +     * Checks that the threads do not terminate within the default
668 +     * millisecond delay of {@code timeoutMillis()}.
669 +     */
670 +    void assertThreadsStayAlive(Thread... threads) {
671 +        assertThreadsStayAlive(timeoutMillis(), threads);
672 +    }
673 +
674 +    /**
675 +     * Checks that the threads do not terminate within the given millisecond delay.
676 +     */
677 +    void assertThreadsStayAlive(long millis, Thread... threads) {
678 +        try {
679 +            // No need to optimize the failing case via Thread.join.
680 +            delay(millis);
681 +            for (Thread thread : threads)
682 +                assertTrue(thread.isAlive());
683 +        } catch (InterruptedException ie) {
684 +            fail("Unexpected InterruptedException");
685 +        }
686 +    }
687 +
688 +    /**
689 +     * Checks that future.get times out, with the default timeout of
690 +     * {@code timeoutMillis()}.
691 +     */
692 +    void assertFutureTimesOut(Future future) {
693 +        assertFutureTimesOut(future, timeoutMillis());
694 +    }
695 +
696 +    /**
697 +     * Checks that future.get times out, with the given millisecond timeout.
698 +     */
699 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
700 +        long startTime = System.nanoTime();
701 +        try {
702 +            future.get(timeoutMillis, MILLISECONDS);
703 +            shouldThrow();
704 +        } catch (TimeoutException success) {
705 +        } catch (Exception e) {
706 +            threadUnexpectedException(e);
707 +        } finally { future.cancel(true); }
708 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
709 +    }
710  
711      /**
712       * Fails with message "should throw exception".
# Line 495 | Line 747 | public class JSR166TestCase extends Test
747      public static final Integer m6  = new Integer(-6);
748      public static final Integer m10 = new Integer(-10);
749  
498
750      /**
751       * Runs Runnable r with a security policy that permits precisely
752       * the specified permissions.  If there is no current security
# Line 507 | Line 758 | public class JSR166TestCase extends Test
758          SecurityManager sm = System.getSecurityManager();
759          if (sm == null) {
760              r.run();
761 +        }
762 +        runWithSecurityManagerWithPermissions(r, permissions);
763 +    }
764 +
765 +    /**
766 +     * Runs Runnable r with a security policy that permits precisely
767 +     * the specified permissions.  If there is no current security
768 +     * manager, a temporary one is set for the duration of the
769 +     * Runnable.  We require that any security manager permit
770 +     * getPolicy/setPolicy.
771 +     */
772 +    public void runWithSecurityManagerWithPermissions(Runnable r,
773 +                                                      Permission... permissions) {
774 +        SecurityManager sm = System.getSecurityManager();
775 +        if (sm == null) {
776              Policy savedPolicy = Policy.getPolicy();
777              try {
778                  Policy.setPolicy(permissivePolicy());
779                  System.setSecurityManager(new SecurityManager());
780 <                runWithPermissions(r, permissions);
780 >                runWithSecurityManagerWithPermissions(r, permissions);
781              } finally {
782                  System.setSecurityManager(null);
783                  Policy.setPolicy(savedPolicy);
# Line 559 | Line 825 | public class JSR166TestCase extends Test
825              return perms.implies(p);
826          }
827          public void refresh() {}
828 +        public String toString() {
829 +            List<Permission> ps = new ArrayList<Permission>();
830 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
831 +                ps.add(e.nextElement());
832 +            return "AdjustablePolicy with permissions " + ps;
833 +        }
834      }
835  
836      /**
# Line 586 | Line 858 | public class JSR166TestCase extends Test
858       */
859      void sleep(long millis) {
860          try {
861 <            Thread.sleep(millis);
861 >            delay(millis);
862          } catch (InterruptedException ie) {
863              AssertionFailedError afe =
864                  new AssertionFailedError("Unexpected InterruptedException");
# Line 596 | Line 868 | public class JSR166TestCase extends Test
868      }
869  
870      /**
871 <     * Sleeps until the timeout has elapsed, or interrupted.
600 <     * Does <em>NOT</em> throw InterruptedException.
601 <     */
602 <    void sleepTillInterrupted(long timeoutMillis) {
603 <        try {
604 <            Thread.sleep(timeoutMillis);
605 <        } catch (InterruptedException wakeup) {}
606 <    }
607 <
608 <    /**
609 <     * Waits up to the specified number of milliseconds for the given
871 >     * Spin-waits up to the specified number of milliseconds for the given
872       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
873       */
874      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
875 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
614 <        long t0 = System.nanoTime();
875 >        long startTime = System.nanoTime();
876          for (;;) {
877              Thread.State s = thread.getState();
878              if (s == Thread.State.BLOCKED ||
879                  s == Thread.State.WAITING ||
880 <                s == Thread.State.TIMED_WAITING ||
881 <                System.nanoTime() - t0 > timeoutNanos)
880 >                s == Thread.State.TIMED_WAITING)
881 >                return;
882 >            else if (s == Thread.State.TERMINATED)
883 >                fail("Unexpected thread termination");
884 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
885 >                threadAssertTrue(thread.isAlive());
886                  return;
887 +            }
888              Thread.yield();
889          }
890      }
891  
892      /**
893 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
894 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
895 +     */
896 +    void waitForThreadToEnterWaitState(Thread thread) {
897 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
898 +    }
899 +
900 +    /**
901       * Returns the number of milliseconds since time given by
902       * startNanoTime, which must have been previously returned from a
903       * call to {@link System.nanoTime()}.
904       */
905 <    long millisElapsedSince(long startNanoTime) {
905 >    static long millisElapsedSince(long startNanoTime) {
906          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
907      }
908 <    
908 >
909      /**
910       * Returns a new started daemon Thread running the given runnable.
911       */
# Line 653 | Line 927 | public class JSR166TestCase extends Test
927          } catch (InterruptedException ie) {
928              threadUnexpectedException(ie);
929          } finally {
930 <            if (t.isAlive()) {
930 >            if (t.getState() != Thread.State.TERMINATED) {
931                  t.interrupt();
932                  fail("Test timed out");
933              }
934          }
935      }
936  
937 +    /**
938 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
939 +     * terminate (using {@link Thread#join(long)}), else interrupts
940 +     * the thread (in the hope that it may terminate later) and fails.
941 +     */
942 +    void awaitTermination(Thread t) {
943 +        awaitTermination(t, LONG_DELAY_MS);
944 +    }
945 +
946      // Some convenient Runnable classes
947  
948      public abstract class CheckedRunnable implements Runnable {
# Line 722 | Line 1005 | public class JSR166TestCase extends Test
1005                  realRun();
1006                  threadShouldThrow("InterruptedException");
1007              } catch (InterruptedException success) {
1008 +                threadAssertFalse(Thread.interrupted());
1009              } catch (Throwable t) {
1010                  threadUnexpectedException(t);
1011              }
# Line 751 | Line 1035 | public class JSR166TestCase extends Test
1035                  threadShouldThrow("InterruptedException");
1036                  return result;
1037              } catch (InterruptedException success) {
1038 +                threadAssertFalse(Thread.interrupted());
1039              } catch (Throwable t) {
1040                  threadUnexpectedException(t);
1041              }
# Line 782 | Line 1067 | public class JSR166TestCase extends Test
1067              }};
1068      }
1069  
1070 +    public Runnable awaiter(final CountDownLatch latch) {
1071 +        return new CheckedRunnable() {
1072 +            public void realRun() throws InterruptedException {
1073 +                await(latch);
1074 +            }};
1075 +    }
1076 +
1077 +    public void await(CountDownLatch latch) {
1078 +        try {
1079 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1080 +        } catch (Throwable t) {
1081 +            threadUnexpectedException(t);
1082 +        }
1083 +    }
1084 +
1085 +    public void await(Semaphore semaphore) {
1086 +        try {
1087 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1088 +        } catch (Throwable t) {
1089 +            threadUnexpectedException(t);
1090 +        }
1091 +    }
1092 +
1093 + //     /**
1094 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1095 + //      */
1096 + //     public void await(AtomicBoolean flag) {
1097 + //         await(flag, LONG_DELAY_MS);
1098 + //     }
1099 +
1100 + //     /**
1101 + //      * Spin-waits up to the specified timeout until flag becomes true.
1102 + //      */
1103 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1104 + //         long startTime = System.nanoTime();
1105 + //         while (!flag.get()) {
1106 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1107 + //                 throw new AssertionFailedError("timed out");
1108 + //             Thread.yield();
1109 + //         }
1110 + //     }
1111 +
1112      public static class NPETask implements Callable<String> {
1113          public String call() { throw new NullPointerException(); }
1114      }
# Line 792 | Line 1119 | public class JSR166TestCase extends Test
1119  
1120      public class ShortRunnable extends CheckedRunnable {
1121          protected void realRun() throws Throwable {
1122 <            Thread.sleep(SHORT_DELAY_MS);
1122 >            delay(SHORT_DELAY_MS);
1123          }
1124      }
1125  
1126      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1127          protected void realRun() throws InterruptedException {
1128 <            Thread.sleep(SHORT_DELAY_MS);
1128 >            delay(SHORT_DELAY_MS);
1129          }
1130      }
1131  
1132      public class SmallRunnable extends CheckedRunnable {
1133          protected void realRun() throws Throwable {
1134 <            Thread.sleep(SMALL_DELAY_MS);
1134 >            delay(SMALL_DELAY_MS);
1135          }
1136      }
1137  
1138      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1139          protected void realRun() {
1140              try {
1141 <                Thread.sleep(SMALL_DELAY_MS);
1141 >                delay(SMALL_DELAY_MS);
1142              } catch (InterruptedException ok) {}
1143          }
1144      }
1145  
1146      public class SmallCallable extends CheckedCallable {
1147          protected Object realCall() throws InterruptedException {
1148 <            Thread.sleep(SMALL_DELAY_MS);
1148 >            delay(SMALL_DELAY_MS);
1149              return Boolean.TRUE;
1150          }
1151      }
1152  
1153      public class MediumRunnable extends CheckedRunnable {
1154          protected void realRun() throws Throwable {
1155 <            Thread.sleep(MEDIUM_DELAY_MS);
1155 >            delay(MEDIUM_DELAY_MS);
1156          }
1157      }
1158  
1159      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1160          protected void realRun() throws InterruptedException {
1161 <            Thread.sleep(MEDIUM_DELAY_MS);
1161 >            delay(MEDIUM_DELAY_MS);
1162          }
1163      }
1164  
# Line 839 | Line 1166 | public class JSR166TestCase extends Test
1166          return new CheckedRunnable() {
1167              protected void realRun() {
1168                  try {
1169 <                    Thread.sleep(timeoutMillis);
1169 >                    delay(timeoutMillis);
1170                  } catch (InterruptedException ok) {}
1171              }};
1172      }
# Line 847 | Line 1174 | public class JSR166TestCase extends Test
1174      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1175          protected void realRun() {
1176              try {
1177 <                Thread.sleep(MEDIUM_DELAY_MS);
1177 >                delay(MEDIUM_DELAY_MS);
1178              } catch (InterruptedException ok) {}
1179          }
1180      }
# Line 855 | Line 1182 | public class JSR166TestCase extends Test
1182      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1183          protected void realRun() {
1184              try {
1185 <                Thread.sleep(LONG_DELAY_MS);
1185 >                delay(LONG_DELAY_MS);
1186              } catch (InterruptedException ok) {}
1187          }
1188      }
# Line 879 | Line 1206 | public class JSR166TestCase extends Test
1206                  public boolean isDone() { return done; }
1207                  public void run() {
1208                      try {
1209 <                        Thread.sleep(timeoutMillis);
1209 >                        delay(timeoutMillis);
1210                          done = true;
1211                      } catch (InterruptedException ok) {}
1212                  }
# Line 890 | Line 1217 | public class JSR166TestCase extends Test
1217          public volatile boolean done = false;
1218          public void run() {
1219              try {
1220 <                Thread.sleep(SHORT_DELAY_MS);
1220 >                delay(SHORT_DELAY_MS);
1221                  done = true;
1222              } catch (InterruptedException ok) {}
1223          }
# Line 900 | Line 1227 | public class JSR166TestCase extends Test
1227          public volatile boolean done = false;
1228          public void run() {
1229              try {
1230 <                Thread.sleep(SMALL_DELAY_MS);
1230 >                delay(SMALL_DELAY_MS);
1231                  done = true;
1232              } catch (InterruptedException ok) {}
1233          }
# Line 910 | Line 1237 | public class JSR166TestCase extends Test
1237          public volatile boolean done = false;
1238          public void run() {
1239              try {
1240 <                Thread.sleep(MEDIUM_DELAY_MS);
1240 >                delay(MEDIUM_DELAY_MS);
1241                  done = true;
1242              } catch (InterruptedException ok) {}
1243          }
# Line 920 | Line 1247 | public class JSR166TestCase extends Test
1247          public volatile boolean done = false;
1248          public void run() {
1249              try {
1250 <                Thread.sleep(LONG_DELAY_MS);
1250 >                delay(LONG_DELAY_MS);
1251                  done = true;
1252              } catch (InterruptedException ok) {}
1253          }
# Line 937 | Line 1264 | public class JSR166TestCase extends Test
1264          public volatile boolean done = false;
1265          public Object call() {
1266              try {
1267 <                Thread.sleep(SMALL_DELAY_MS);
1267 >                delay(SMALL_DELAY_MS);
1268                  done = true;
1269              } catch (InterruptedException ok) {}
1270              return Boolean.TRUE;
# Line 950 | Line 1277 | public class JSR166TestCase extends Test
1277      public abstract class CheckedRecursiveAction extends RecursiveAction {
1278          protected abstract void realCompute() throws Throwable;
1279  
1280 <        public final void compute() {
1280 >        @Override protected final void compute() {
1281              try {
1282                  realCompute();
1283              } catch (Throwable t) {
# Line 965 | Line 1292 | public class JSR166TestCase extends Test
1292      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1293          protected abstract T realCompute() throws Throwable;
1294  
1295 <        public final T compute() {
1295 >        @Override protected final T compute() {
1296              try {
1297                  return realCompute();
1298              } catch (Throwable t) {
# Line 984 | Line 1311 | public class JSR166TestCase extends Test
1311      }
1312  
1313      /**
1314 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1315 <     * of throwing checked exceptions.
1314 >     * A CyclicBarrier that uses timed await and fails with
1315 >     * AssertionFailedErrors instead of throwing checked exceptions.
1316       */
1317      public class CheckedBarrier extends CyclicBarrier {
1318          public CheckedBarrier(int parties) { super(parties); }
1319  
1320          public int await() {
1321              try {
1322 <                return super.await();
1322 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1323 >            } catch (TimeoutException e) {
1324 >                throw new AssertionFailedError("timed out");
1325              } catch (Exception e) {
1326                  AssertionFailedError afe =
1327                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1002 | Line 1331 | public class JSR166TestCase extends Test
1331          }
1332      }
1333  
1334 +    void checkEmpty(BlockingQueue q) {
1335 +        try {
1336 +            assertTrue(q.isEmpty());
1337 +            assertEquals(0, q.size());
1338 +            assertNull(q.peek());
1339 +            assertNull(q.poll());
1340 +            assertNull(q.poll(0, MILLISECONDS));
1341 +            assertEquals(q.toString(), "[]");
1342 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1343 +            assertFalse(q.iterator().hasNext());
1344 +            try {
1345 +                q.element();
1346 +                shouldThrow();
1347 +            } catch (NoSuchElementException success) {}
1348 +            try {
1349 +                q.iterator().next();
1350 +                shouldThrow();
1351 +            } catch (NoSuchElementException success) {}
1352 +            try {
1353 +                q.remove();
1354 +                shouldThrow();
1355 +            } catch (NoSuchElementException success) {}
1356 +        } catch (InterruptedException ie) {
1357 +            threadUnexpectedException(ie);
1358 +        }
1359 +    }
1360 +
1361 +    void assertSerialEquals(Object x, Object y) {
1362 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1363 +    }
1364 +
1365 +    void assertNotSerialEquals(Object x, Object y) {
1366 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1367 +    }
1368 +
1369 +    byte[] serialBytes(Object o) {
1370 +        try {
1371 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1372 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1373 +            oos.writeObject(o);
1374 +            oos.flush();
1375 +            oos.close();
1376 +            return bos.toByteArray();
1377 +        } catch (Throwable t) {
1378 +            threadUnexpectedException(t);
1379 +            return new byte[0];
1380 +        }
1381 +    }
1382 +
1383 +    @SuppressWarnings("unchecked")
1384 +    <T> T serialClone(T o) {
1385 +        try {
1386 +            ObjectInputStream ois = new ObjectInputStream
1387 +                (new ByteArrayInputStream(serialBytes(o)));
1388 +            T clone = (T) ois.readObject();
1389 +            assertSame(o.getClass(), clone.getClass());
1390 +            return clone;
1391 +        } catch (Throwable t) {
1392 +            threadUnexpectedException(t);
1393 +            return null;
1394 +        }
1395 +    }
1396 +
1397 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1398 +                             Runnable... throwingActions) {
1399 +        for (Runnable throwingAction : throwingActions) {
1400 +            boolean threw = false;
1401 +            try { throwingAction.run(); }
1402 +            catch (Throwable t) {
1403 +                threw = true;
1404 +                if (!expectedExceptionClass.isInstance(t)) {
1405 +                    AssertionFailedError afe =
1406 +                        new AssertionFailedError
1407 +                        ("Expected " + expectedExceptionClass.getName() +
1408 +                         ", got " + t.getClass().getName());
1409 +                    afe.initCause(t);
1410 +                    threadUnexpectedException(afe);
1411 +                }
1412 +            }
1413 +            if (!threw)
1414 +                shouldThrow(expectedExceptionClass.getName());
1415 +        }
1416 +    }
1417   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines