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.61 by jsr166, Mon Oct 11 03:54:10 2010 UTC vs.
Revision 1.113 by dl, Sun Sep 8 23:00:36 2013 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.security.CodeSource;
30   import java.security.Permission;
31   import java.security.PermissionCollection;
# Line 60 | Line 75 | import java.security.SecurityPermission;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 96 | Line 111 | public class JSR166TestCase extends Test
111      private static final boolean useSecurityManager =
112          Boolean.getBoolean("jsr166.useSecurityManager");
113  
114 +    protected static final boolean expensiveTests =
115 +        Boolean.getBoolean("jsr166.expensiveTests");
116 +
117      /**
118       * If true, report on stdout all "slow" tests, that is, ones that
119       * take more than profileThreshold milliseconds to execute.
# Line 110 | Line 128 | public class JSR166TestCase extends Test
128      private static final long profileThreshold =
129          Long.getLong("jsr166.profileThreshold", 100);
130  
131 +    /**
132 +     * The number of repetitions per test (for tickling rare bugs).
133 +     */
134 +    private static final int runsPerTest =
135 +        Integer.getInteger("jsr166.runsPerTest", 1);
136 +
137      protected void runTest() throws Throwable {
138 <        if (profileTests)
139 <            runTestProfiled();
140 <        else
141 <            super.runTest();
138 >        for (int i = 0; i < runsPerTest; i++) {
139 >            if (profileTests)
140 >                runTestProfiled();
141 >            else
142 >                super.runTest();
143 >        }
144      }
145  
146      protected void runTestProfiled() throws Throwable {
# Line 128 | Line 154 | public class JSR166TestCase extends Test
154                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
155          }
156      }
157 <    
157 >
158      /**
159 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
159 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
160 >     * Optional command line arg provides the number of iterations to
161 >     * repeat running the tests.
162       */
163      public static void main(String[] args) {
164          if (useSecurityManager) {
# Line 162 | Line 190 | public class JSR166TestCase extends Test
190          return suite;
191      }
192  
193 +    public static void addNamedTestClasses(TestSuite suite,
194 +                                           String... testClassNames) {
195 +        for (String testClassName : testClassNames) {
196 +            try {
197 +                Class<?> testClass = Class.forName(testClassName);
198 +                Method m = testClass.getDeclaredMethod("suite",
199 +                                                       new Class<?>[0]);
200 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
201 +            } catch (Exception e) {
202 +                throw new Error("Missing test class", e);
203 +            }
204 +        }
205 +    }
206 +
207 +    public static final double JAVA_CLASS_VERSION;
208 +    static {
209 +        try {
210 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
211 +                new java.security.PrivilegedAction<Double>() {
212 +                public Double run() {
213 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
214 +        } catch (Throwable t) {
215 +            throw new Error(t);
216 +        }
217 +    }
218 +
219 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
220 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
221 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
222 +
223      /**
224       * Collects all JSR166 unit tests as one suite.
225       */
226      public static Test suite() {
227 <        return newTestSuite(
227 >        // Java7+ test classes
228 >        TestSuite suite = newTestSuite(
229              ForkJoinPoolTest.suite(),
230              ForkJoinTaskTest.suite(),
231              RecursiveActionTest.suite(),
# Line 231 | Line 290 | public class JSR166TestCase extends Test
290              TreeSetTest.suite(),
291              TreeSubMapTest.suite(),
292              TreeSubSetTest.suite());
293 +
294 +        // Java8+ test classes
295 +        if (atLeastJava8()) {
296 +            String[] java8TestClassNames = {
297 +                "Atomic8Test",
298 +                "CompletableFutureTest",
299 +                "ConcurrentHashMap8Test",
300 +                "CountedCompleterTest",
301 +                "DoubleAccumulatorTest",
302 +                "DoubleAdderTest",
303 +                "ForkJoinPool8Test",
304 +                "ForkJoinTask8Test",
305 +                "LongAccumulatorTest",
306 +                "LongAdderTest",
307 +                "SplittableRandomTest",
308 +                "StampedLockTest",
309 +                "ThreadLocalRandom8Test",
310 +            };
311 +            addNamedTestClasses(suite, java8TestClassNames);
312 +        }
313 +
314 +        return suite;
315      }
316  
317 +    // Delays for timing-dependent tests, in milliseconds.
318  
319      public static long SHORT_DELAY_MS;
320      public static long SMALL_DELAY_MS;
321      public static long MEDIUM_DELAY_MS;
322      public static long LONG_DELAY_MS;
323  
242
324      /**
325       * Returns the shortest timed delay. This could
326       * be reimplemented to use for example a Property.
# Line 248 | Line 329 | public class JSR166TestCase extends Test
329          return 50;
330      }
331  
251
332      /**
333       * Sets delays as multiples of SHORT_DELAY.
334       */
# Line 256 | Line 336 | public class JSR166TestCase extends Test
336          SHORT_DELAY_MS = getShortDelay();
337          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
338          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
339 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
339 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
340 >    }
341 >
342 >    /**
343 >     * Returns a timeout in milliseconds to be used in tests that
344 >     * verify that operations block or time out.
345 >     */
346 >    long timeoutMillis() {
347 >        return SHORT_DELAY_MS / 4;
348 >    }
349 >
350 >    /**
351 >     * Returns a new Date instance representing a time delayMillis
352 >     * milliseconds in the future.
353 >     */
354 >    Date delayedDate(long delayMillis) {
355 >        return new Date(System.currentTimeMillis() + delayMillis);
356      }
357  
358      /**
# Line 280 | Line 376 | public class JSR166TestCase extends Test
376      }
377  
378      /**
379 +     * Extra checks that get done for all test cases.
380 +     *
381       * Triggers test case failure if any thread assertions have failed,
382       * by rethrowing, in the test harness thread, any exception recorded
383       * earlier by threadRecordFailure.
384 +     *
385 +     * Triggers test case failure if interrupt status is set in the main thread.
386       */
387      public void tearDown() throws Exception {
388 <        Throwable t = threadFailure.get();
388 >        Throwable t = threadFailure.getAndSet(null);
389          if (t != null) {
390              if (t instanceof Error)
391                  throw (Error) t;
# Line 300 | Line 400 | public class JSR166TestCase extends Test
400                  throw afe;
401              }
402          }
403 +
404 +        if (Thread.interrupted())
405 +            throw new AssertionFailedError("interrupt status set in main thread");
406 +
407 +        checkForkJoinPoolThreadLeaks();
408 +    }
409 +
410 +    /**
411 +     * Find missing try { ... } finally { joinPool(e); }
412 +     */
413 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
414 +        Thread[] survivors = new Thread[5];
415 +        int count = Thread.enumerate(survivors);
416 +        for (int i = 0; i < count; i++) {
417 +            Thread thread = survivors[i];
418 +            String name = thread.getName();
419 +            if (name.startsWith("ForkJoinPool-")) {
420 +                // give thread some time to terminate
421 +                thread.join(LONG_DELAY_MS);
422 +                if (!thread.isAlive()) continue;
423 +                thread.stop();
424 +                throw new AssertionFailedError
425 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
426 +                                   toString(), name));
427 +            }
428 +        }
429      }
430  
431      /**
# Line 431 | Line 557 | public class JSR166TestCase extends Test
557          else {
558              AssertionFailedError afe =
559                  new AssertionFailedError("unexpected exception: " + t);
560 <            t.initCause(t);
560 >            afe.initCause(t);
561              throw afe;
562          }
563      }
564  
565      /**
566 +     * Delays, via Thread.sleep, for the given millisecond delay, but
567 +     * if the sleep is shorter than specified, may re-sleep or yield
568 +     * until time elapses.
569 +     */
570 +    static void delay(long millis) throws InterruptedException {
571 +        long startTime = System.nanoTime();
572 +        long ns = millis * 1000 * 1000;
573 +        for (;;) {
574 +            if (millis > 0L)
575 +                Thread.sleep(millis);
576 +            else // too short to sleep
577 +                Thread.yield();
578 +            long d = ns - (System.nanoTime() - startTime);
579 +            if (d > 0L)
580 +                millis = d / (1000 * 1000);
581 +            else
582 +                break;
583 +        }
584 +    }
585 +
586 +    /**
587       * Waits out termination of a thread pool or fails doing so.
588       */
589 <    public void joinPool(ExecutorService exec) {
589 >    void joinPool(ExecutorService exec) {
590          try {
591              exec.shutdown();
592              assertTrue("ExecutorService did not terminate in a timely manner",
593 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
593 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
594          } catch (SecurityException ok) {
595              // Allowed in case test doesn't have privs
596          } catch (InterruptedException ie) {
# Line 451 | Line 598 | public class JSR166TestCase extends Test
598          }
599      }
600  
601 +    /**
602 +     * A debugging tool to print all stack traces, as jstack does.
603 +     */
604 +    static void printAllStackTraces() {
605 +        for (ThreadInfo info :
606 +                 ManagementFactory.getThreadMXBean()
607 +                 .dumpAllThreads(true, true))
608 +            System.err.print(info);
609 +    }
610 +
611 +    /**
612 +     * Checks that thread does not terminate within the default
613 +     * millisecond delay of {@code timeoutMillis()}.
614 +     */
615 +    void assertThreadStaysAlive(Thread thread) {
616 +        assertThreadStaysAlive(thread, timeoutMillis());
617 +    }
618 +
619 +    /**
620 +     * Checks that thread does not terminate within the given millisecond delay.
621 +     */
622 +    void assertThreadStaysAlive(Thread thread, long millis) {
623 +        try {
624 +            // No need to optimize the failing case via Thread.join.
625 +            delay(millis);
626 +            assertTrue(thread.isAlive());
627 +        } catch (InterruptedException ie) {
628 +            fail("Unexpected InterruptedException");
629 +        }
630 +    }
631 +
632 +    /**
633 +     * Checks that the threads do not terminate within the default
634 +     * millisecond delay of {@code timeoutMillis()}.
635 +     */
636 +    void assertThreadsStayAlive(Thread... threads) {
637 +        assertThreadsStayAlive(timeoutMillis(), threads);
638 +    }
639 +
640 +    /**
641 +     * Checks that the threads do not terminate within the given millisecond delay.
642 +     */
643 +    void assertThreadsStayAlive(long millis, Thread... threads) {
644 +        try {
645 +            // No need to optimize the failing case via Thread.join.
646 +            delay(millis);
647 +            for (Thread thread : threads)
648 +                assertTrue(thread.isAlive());
649 +        } catch (InterruptedException ie) {
650 +            fail("Unexpected InterruptedException");
651 +        }
652 +    }
653 +
654 +    /**
655 +     * Checks that future.get times out, with the default timeout of
656 +     * {@code timeoutMillis()}.
657 +     */
658 +    void assertFutureTimesOut(Future future) {
659 +        assertFutureTimesOut(future, timeoutMillis());
660 +    }
661 +
662 +    /**
663 +     * Checks that future.get times out, with the given millisecond timeout.
664 +     */
665 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
666 +        long startTime = System.nanoTime();
667 +        try {
668 +            future.get(timeoutMillis, MILLISECONDS);
669 +            shouldThrow();
670 +        } catch (TimeoutException success) {
671 +        } catch (Exception e) {
672 +            threadUnexpectedException(e);
673 +        } finally { future.cancel(true); }
674 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
675 +    }
676  
677      /**
678       * Fails with message "should throw exception".
# Line 491 | Line 713 | public class JSR166TestCase extends Test
713      public static final Integer m6  = new Integer(-6);
714      public static final Integer m10 = new Integer(-10);
715  
494
716      /**
717       * Runs Runnable r with a security policy that permits precisely
718       * the specified permissions.  If there is no current security
# Line 503 | Line 724 | public class JSR166TestCase extends Test
724          SecurityManager sm = System.getSecurityManager();
725          if (sm == null) {
726              r.run();
727 +        }
728 +        runWithSecurityManagerWithPermissions(r, permissions);
729 +    }
730 +
731 +    /**
732 +     * Runs Runnable r with a security policy that permits precisely
733 +     * the specified permissions.  If there is no current security
734 +     * manager, a temporary one is set for the duration of the
735 +     * Runnable.  We require that any security manager permit
736 +     * getPolicy/setPolicy.
737 +     */
738 +    public void runWithSecurityManagerWithPermissions(Runnable r,
739 +                                                      Permission... permissions) {
740 +        SecurityManager sm = System.getSecurityManager();
741 +        if (sm == null) {
742              Policy savedPolicy = Policy.getPolicy();
743              try {
744                  Policy.setPolicy(permissivePolicy());
745                  System.setSecurityManager(new SecurityManager());
746 <                runWithPermissions(r, permissions);
746 >                runWithSecurityManagerWithPermissions(r, permissions);
747              } finally {
748                  System.setSecurityManager(null);
749                  Policy.setPolicy(savedPolicy);
# Line 555 | Line 791 | public class JSR166TestCase extends Test
791              return perms.implies(p);
792          }
793          public void refresh() {}
794 +        public String toString() {
795 +            List<Permission> ps = new ArrayList<Permission>();
796 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
797 +                ps.add(e.nextElement());
798 +            return "AdjustablePolicy with permissions " + ps;
799 +        }
800      }
801  
802      /**
# Line 582 | Line 824 | public class JSR166TestCase extends Test
824       */
825      void sleep(long millis) {
826          try {
827 <            Thread.sleep(millis);
827 >            delay(millis);
828          } catch (InterruptedException ie) {
829              AssertionFailedError afe =
830                  new AssertionFailedError("Unexpected InterruptedException");
# Line 592 | Line 834 | public class JSR166TestCase extends Test
834      }
835  
836      /**
837 <     * Sleeps until the timeout has elapsed, or interrupted.
838 <     * Does <em>NOT</em> throw InterruptedException.
837 >     * Spin-waits up to the specified number of milliseconds for the given
838 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
839       */
840 <    void sleepTillInterrupted(long timeoutMillis) {
841 <        try {
842 <            Thread.sleep(timeoutMillis);
843 <        } catch (InterruptedException wakeup) {}
840 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
841 >        long startTime = System.nanoTime();
842 >        for (;;) {
843 >            Thread.State s = thread.getState();
844 >            if (s == Thread.State.BLOCKED ||
845 >                s == Thread.State.WAITING ||
846 >                s == Thread.State.TIMED_WAITING)
847 >                return;
848 >            else if (s == Thread.State.TERMINATED)
849 >                fail("Unexpected thread termination");
850 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
851 >                threadAssertTrue(thread.isAlive());
852 >                return;
853 >            }
854 >            Thread.yield();
855 >        }
856 >    }
857 >
858 >    /**
859 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
860 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
861 >     */
862 >    void waitForThreadToEnterWaitState(Thread thread) {
863 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
864 >    }
865 >
866 >    /**
867 >     * Returns the number of milliseconds since time given by
868 >     * startNanoTime, which must have been previously returned from a
869 >     * call to {@link System.nanoTime()}.
870 >     */
871 >    long millisElapsedSince(long startNanoTime) {
872 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
873      }
874  
875      /**
# Line 622 | Line 893 | public class JSR166TestCase extends Test
893          } catch (InterruptedException ie) {
894              threadUnexpectedException(ie);
895          } finally {
896 <            if (t.isAlive()) {
896 >            if (t.getState() != Thread.State.TERMINATED) {
897                  t.interrupt();
898                  fail("Test timed out");
899              }
900          }
901      }
902  
903 +    /**
904 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
905 +     * terminate (using {@link Thread#join(long)}), else interrupts
906 +     * the thread (in the hope that it may terminate later) and fails.
907 +     */
908 +    void awaitTermination(Thread t) {
909 +        awaitTermination(t, LONG_DELAY_MS);
910 +    }
911 +
912      // Some convenient Runnable classes
913  
914      public abstract class CheckedRunnable implements Runnable {
# Line 691 | Line 971 | public class JSR166TestCase extends Test
971                  realRun();
972                  threadShouldThrow("InterruptedException");
973              } catch (InterruptedException success) {
974 +                threadAssertFalse(Thread.interrupted());
975              } catch (Throwable t) {
976                  threadUnexpectedException(t);
977              }
# Line 720 | Line 1001 | public class JSR166TestCase extends Test
1001                  threadShouldThrow("InterruptedException");
1002                  return result;
1003              } catch (InterruptedException success) {
1004 +                threadAssertFalse(Thread.interrupted());
1005              } catch (Throwable t) {
1006                  threadUnexpectedException(t);
1007              }
# Line 743 | Line 1025 | public class JSR166TestCase extends Test
1025  
1026      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1027          return new CheckedCallable<String>() {
1028 <            public String realCall() {
1028 >            protected String realCall() {
1029                  try {
1030                      latch.await();
1031                  } catch (InterruptedException quittingTime) {}
# Line 751 | Line 1033 | public class JSR166TestCase extends Test
1033              }};
1034      }
1035  
1036 +    public Runnable awaiter(final CountDownLatch latch) {
1037 +        return new CheckedRunnable() {
1038 +            public void realRun() throws InterruptedException {
1039 +                await(latch);
1040 +            }};
1041 +    }
1042 +
1043 +    public void await(CountDownLatch latch) {
1044 +        try {
1045 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1046 +        } catch (Throwable t) {
1047 +            threadUnexpectedException(t);
1048 +        }
1049 +    }
1050 +
1051 +    public void await(Semaphore semaphore) {
1052 +        try {
1053 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1054 +        } catch (Throwable t) {
1055 +            threadUnexpectedException(t);
1056 +        }
1057 +    }
1058 +
1059 + //     /**
1060 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1061 + //      */
1062 + //     public void await(AtomicBoolean flag) {
1063 + //         await(flag, LONG_DELAY_MS);
1064 + //     }
1065 +
1066 + //     /**
1067 + //      * Spin-waits up to the specified timeout until flag becomes true.
1068 + //      */
1069 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1070 + //         long startTime = System.nanoTime();
1071 + //         while (!flag.get()) {
1072 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1073 + //                 throw new AssertionFailedError("timed out");
1074 + //             Thread.yield();
1075 + //         }
1076 + //     }
1077 +
1078      public static class NPETask implements Callable<String> {
1079          public String call() { throw new NullPointerException(); }
1080      }
# Line 761 | Line 1085 | public class JSR166TestCase extends Test
1085  
1086      public class ShortRunnable extends CheckedRunnable {
1087          protected void realRun() throws Throwable {
1088 <            Thread.sleep(SHORT_DELAY_MS);
1088 >            delay(SHORT_DELAY_MS);
1089          }
1090      }
1091  
1092      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1093          protected void realRun() throws InterruptedException {
1094 <            Thread.sleep(SHORT_DELAY_MS);
1094 >            delay(SHORT_DELAY_MS);
1095          }
1096      }
1097  
1098      public class SmallRunnable extends CheckedRunnable {
1099          protected void realRun() throws Throwable {
1100 <            Thread.sleep(SMALL_DELAY_MS);
1100 >            delay(SMALL_DELAY_MS);
1101          }
1102      }
1103  
1104      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1105          protected void realRun() {
1106              try {
1107 <                Thread.sleep(SMALL_DELAY_MS);
1107 >                delay(SMALL_DELAY_MS);
1108              } catch (InterruptedException ok) {}
1109          }
1110      }
1111  
1112      public class SmallCallable extends CheckedCallable {
1113          protected Object realCall() throws InterruptedException {
1114 <            Thread.sleep(SMALL_DELAY_MS);
1114 >            delay(SMALL_DELAY_MS);
1115              return Boolean.TRUE;
1116          }
1117      }
1118  
1119      public class MediumRunnable extends CheckedRunnable {
1120          protected void realRun() throws Throwable {
1121 <            Thread.sleep(MEDIUM_DELAY_MS);
1121 >            delay(MEDIUM_DELAY_MS);
1122          }
1123      }
1124  
1125      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1126          protected void realRun() throws InterruptedException {
1127 <            Thread.sleep(MEDIUM_DELAY_MS);
1127 >            delay(MEDIUM_DELAY_MS);
1128          }
1129      }
1130  
1131 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1132 +        return new CheckedRunnable() {
1133 +            protected void realRun() {
1134 +                try {
1135 +                    delay(timeoutMillis);
1136 +                } catch (InterruptedException ok) {}
1137 +            }};
1138 +    }
1139 +
1140      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1141          protected void realRun() {
1142              try {
1143 <                Thread.sleep(MEDIUM_DELAY_MS);
1143 >                delay(MEDIUM_DELAY_MS);
1144              } catch (InterruptedException ok) {}
1145          }
1146      }
# Line 815 | Line 1148 | public class JSR166TestCase extends Test
1148      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1149          protected void realRun() {
1150              try {
1151 <                Thread.sleep(LONG_DELAY_MS);
1151 >                delay(LONG_DELAY_MS);
1152              } catch (InterruptedException ok) {}
1153          }
1154      }
# Line 839 | Line 1172 | public class JSR166TestCase extends Test
1172                  public boolean isDone() { return done; }
1173                  public void run() {
1174                      try {
1175 <                        Thread.sleep(timeoutMillis);
1175 >                        delay(timeoutMillis);
1176                          done = true;
1177                      } catch (InterruptedException ok) {}
1178                  }
# Line 850 | Line 1183 | public class JSR166TestCase extends Test
1183          public volatile boolean done = false;
1184          public void run() {
1185              try {
1186 <                Thread.sleep(SHORT_DELAY_MS);
1186 >                delay(SHORT_DELAY_MS);
1187                  done = true;
1188              } catch (InterruptedException ok) {}
1189          }
# Line 860 | Line 1193 | public class JSR166TestCase extends Test
1193          public volatile boolean done = false;
1194          public void run() {
1195              try {
1196 <                Thread.sleep(SMALL_DELAY_MS);
1196 >                delay(SMALL_DELAY_MS);
1197                  done = true;
1198              } catch (InterruptedException ok) {}
1199          }
# Line 870 | Line 1203 | public class JSR166TestCase extends Test
1203          public volatile boolean done = false;
1204          public void run() {
1205              try {
1206 <                Thread.sleep(MEDIUM_DELAY_MS);
1206 >                delay(MEDIUM_DELAY_MS);
1207                  done = true;
1208              } catch (InterruptedException ok) {}
1209          }
# Line 880 | Line 1213 | public class JSR166TestCase extends Test
1213          public volatile boolean done = false;
1214          public void run() {
1215              try {
1216 <                Thread.sleep(LONG_DELAY_MS);
1216 >                delay(LONG_DELAY_MS);
1217                  done = true;
1218              } catch (InterruptedException ok) {}
1219          }
# Line 897 | Line 1230 | public class JSR166TestCase extends Test
1230          public volatile boolean done = false;
1231          public Object call() {
1232              try {
1233 <                Thread.sleep(SMALL_DELAY_MS);
1233 >                delay(SMALL_DELAY_MS);
1234                  done = true;
1235              } catch (InterruptedException ok) {}
1236              return Boolean.TRUE;
# Line 910 | Line 1243 | public class JSR166TestCase extends Test
1243      public abstract class CheckedRecursiveAction extends RecursiveAction {
1244          protected abstract void realCompute() throws Throwable;
1245  
1246 <        public final void compute() {
1246 >        @Override protected final void compute() {
1247              try {
1248                  realCompute();
1249              } catch (Throwable t) {
# Line 925 | Line 1258 | public class JSR166TestCase extends Test
1258      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1259          protected abstract T realCompute() throws Throwable;
1260  
1261 <        public final T compute() {
1261 >        @Override protected final T compute() {
1262              try {
1263                  return realCompute();
1264              } catch (Throwable t) {
# Line 944 | Line 1277 | public class JSR166TestCase extends Test
1277      }
1278  
1279      /**
1280 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1281 <     * of throwing checked exceptions.
1280 >     * A CyclicBarrier that uses timed await and fails with
1281 >     * AssertionFailedErrors instead of throwing checked exceptions.
1282       */
1283      public class CheckedBarrier extends CyclicBarrier {
1284          public CheckedBarrier(int parties) { super(parties); }
1285  
1286          public int await() {
1287              try {
1288 <                return super.await();
1288 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1289 >            } catch (TimeoutException e) {
1290 >                throw new AssertionFailedError("timed out");
1291              } catch (Exception e) {
1292                  AssertionFailedError afe =
1293                      new AssertionFailedError("Unexpected exception: " + e);
# Line 962 | Line 1297 | public class JSR166TestCase extends Test
1297          }
1298      }
1299  
1300 +    void checkEmpty(BlockingQueue q) {
1301 +        try {
1302 +            assertTrue(q.isEmpty());
1303 +            assertEquals(0, q.size());
1304 +            assertNull(q.peek());
1305 +            assertNull(q.poll());
1306 +            assertNull(q.poll(0, MILLISECONDS));
1307 +            assertEquals(q.toString(), "[]");
1308 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1309 +            assertFalse(q.iterator().hasNext());
1310 +            try {
1311 +                q.element();
1312 +                shouldThrow();
1313 +            } catch (NoSuchElementException success) {}
1314 +            try {
1315 +                q.iterator().next();
1316 +                shouldThrow();
1317 +            } catch (NoSuchElementException success) {}
1318 +            try {
1319 +                q.remove();
1320 +                shouldThrow();
1321 +            } catch (NoSuchElementException success) {}
1322 +        } catch (InterruptedException ie) {
1323 +            threadUnexpectedException(ie);
1324 +        }
1325 +    }
1326 +
1327 +    void assertSerialEquals(Object x, Object y) {
1328 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1329 +    }
1330 +
1331 +    void assertNotSerialEquals(Object x, Object y) {
1332 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1333 +    }
1334 +
1335 +    byte[] serialBytes(Object o) {
1336 +        try {
1337 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1338 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1339 +            oos.writeObject(o);
1340 +            oos.flush();
1341 +            oos.close();
1342 +            return bos.toByteArray();
1343 +        } catch (Throwable t) {
1344 +            threadUnexpectedException(t);
1345 +            return new byte[0];
1346 +        }
1347 +    }
1348 +
1349 +    @SuppressWarnings("unchecked")
1350 +    <T> T serialClone(T o) {
1351 +        try {
1352 +            ObjectInputStream ois = new ObjectInputStream
1353 +                (new ByteArrayInputStream(serialBytes(o)));
1354 +            T clone = (T) ois.readObject();
1355 +            assertSame(o.getClass(), clone.getClass());
1356 +            return clone;
1357 +        } catch (Throwable t) {
1358 +            threadUnexpectedException(t);
1359 +            return null;
1360 +        }
1361 +    }
1362 +
1363 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1364 +                             Runnable... throwingActions) {
1365 +        for (Runnable throwingAction : throwingActions) {
1366 +            boolean threw = false;
1367 +            try { throwingAction.run(); }
1368 +            catch (Throwable t) {
1369 +                threw = true;
1370 +                if (!expectedExceptionClass.isInstance(t)) {
1371 +                    AssertionFailedError afe =
1372 +                        new AssertionFailedError
1373 +                        ("Expected " + expectedExceptionClass.getName() +
1374 +                         ", got " + t.getClass().getName());
1375 +                    afe.initCause(t);
1376 +                    threadUnexpectedException(afe);
1377 +                }
1378 +            }
1379 +            if (!threw)
1380 +                shouldThrow(expectedExceptionClass.getName());
1381 +        }
1382 +    }
1383   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines