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.75 by jsr166, Tue May 3 06:08:49 2011 UTC vs.
Revision 1.112 by jsr166, Fri Aug 16 07:07:01 2013 UTC

# Line 7 | Line 7
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;
# Line 63 | 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 116 | 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 136 | Line 156 | public class JSR166TestCase extends Test
156      }
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 168 | 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 237 | 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 +                "CompletableFutureTest",
298 +                "ConcurrentHashMap8Test",
299 +                "CountedCompleterTest",
300 +                "DoubleAccumulatorTest",
301 +                "DoubleAdderTest",
302 +                "ForkJoinPool8Test",
303 +                "ForkJoinTask8Test",
304 +                "LongAccumulatorTest",
305 +                "LongAdderTest",
306 +                "SplittableRandomTest",
307 +                "StampedLockTest",
308 +                "ThreadLocalRandom8Test",
309 +            };
310 +            addNamedTestClasses(suite, java8TestClassNames);
311 +        }
312 +
313 +        return suite;
314      }
315  
316 +    // Delays for timing-dependent tests, in milliseconds.
317  
318      public static long SHORT_DELAY_MS;
319      public static long SMALL_DELAY_MS;
320      public static long MEDIUM_DELAY_MS;
321      public static long LONG_DELAY_MS;
322  
248
323      /**
324       * Returns the shortest timed delay. This could
325       * be reimplemented to use for example a Property.
# Line 254 | Line 328 | public class JSR166TestCase extends Test
328          return 50;
329      }
330  
257
331      /**
332       * Sets delays as multiples of SHORT_DELAY.
333       */
# Line 266 | Line 339 | public class JSR166TestCase extends Test
339      }
340  
341      /**
342 +     * Returns a timeout in milliseconds to be used in tests that
343 +     * verify that operations block or time out.
344 +     */
345 +    long timeoutMillis() {
346 +        return SHORT_DELAY_MS / 4;
347 +    }
348 +
349 +    /**
350 +     * Returns a new Date instance representing a time delayMillis
351 +     * milliseconds in the future.
352 +     */
353 +    Date delayedDate(long delayMillis) {
354 +        return new Date(System.currentTimeMillis() + delayMillis);
355 +    }
356 +
357 +    /**
358       * The first exception encountered if any threadAssertXXX method fails.
359       */
360      private final AtomicReference<Throwable> threadFailure
# Line 286 | Line 375 | public class JSR166TestCase extends Test
375      }
376  
377      /**
378 +     * Extra checks that get done for all test cases.
379 +     *
380       * Triggers test case failure if any thread assertions have failed,
381       * by rethrowing, in the test harness thread, any exception recorded
382       * earlier by threadRecordFailure.
383 +     *
384 +     * Triggers test case failure if interrupt status is set in the main thread.
385       */
386      public void tearDown() throws Exception {
387          Throwable t = threadFailure.getAndSet(null);
# Line 306 | Line 399 | public class JSR166TestCase extends Test
399                  throw afe;
400              }
401          }
402 +
403 +        if (Thread.interrupted())
404 +            throw new AssertionFailedError("interrupt status set in main thread");
405 +
406 +        checkForkJoinPoolThreadLeaks();
407 +    }
408 +
409 +    /**
410 +     * Find missing try { ... } finally { joinPool(e); }
411 +     */
412 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
413 +        Thread[] survivors = new Thread[5];
414 +        int count = Thread.enumerate(survivors);
415 +        for (int i = 0; i < count; i++) {
416 +            Thread thread = survivors[i];
417 +            String name = thread.getName();
418 +            if (name.startsWith("ForkJoinPool-")) {
419 +                // give thread some time to terminate
420 +                thread.join(LONG_DELAY_MS);
421 +                if (!thread.isAlive()) continue;
422 +                thread.stop();
423 +                throw new AssertionFailedError
424 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
425 +                                   toString(), name));
426 +            }
427 +        }
428      }
429  
430      /**
# Line 437 | Line 556 | public class JSR166TestCase extends Test
556          else {
557              AssertionFailedError afe =
558                  new AssertionFailedError("unexpected exception: " + t);
559 <            t.initCause(t);
559 >            afe.initCause(t);
560              throw afe;
561          }
562      }
563  
564      /**
565 +     * Delays, via Thread.sleep, for the given millisecond delay, but
566 +     * if the sleep is shorter than specified, may re-sleep or yield
567 +     * until time elapses.
568 +     */
569 +    static void delay(long millis) throws InterruptedException {
570 +        long startTime = System.nanoTime();
571 +        long ns = millis * 1000 * 1000;
572 +        for (;;) {
573 +            if (millis > 0L)
574 +                Thread.sleep(millis);
575 +            else // too short to sleep
576 +                Thread.yield();
577 +            long d = ns - (System.nanoTime() - startTime);
578 +            if (d > 0L)
579 +                millis = d / (1000 * 1000);
580 +            else
581 +                break;
582 +        }
583 +    }
584 +
585 +    /**
586       * Waits out termination of a thread pool or fails doing so.
587       */
588 <    public void joinPool(ExecutorService exec) {
588 >    void joinPool(ExecutorService exec) {
589          try {
590              exec.shutdown();
591              assertTrue("ExecutorService did not terminate in a timely manner",
# Line 457 | Line 597 | public class JSR166TestCase extends Test
597          }
598      }
599  
600 +    /**
601 +     * A debugging tool to print all stack traces, as jstack does.
602 +     */
603 +    static void printAllStackTraces() {
604 +        for (ThreadInfo info :
605 +                 ManagementFactory.getThreadMXBean()
606 +                 .dumpAllThreads(true, true))
607 +            System.err.print(info);
608 +    }
609 +
610 +    /**
611 +     * Checks that thread does not terminate within the default
612 +     * millisecond delay of {@code timeoutMillis()}.
613 +     */
614 +    void assertThreadStaysAlive(Thread thread) {
615 +        assertThreadStaysAlive(thread, timeoutMillis());
616 +    }
617 +
618 +    /**
619 +     * Checks that thread does not terminate within the given millisecond delay.
620 +     */
621 +    void assertThreadStaysAlive(Thread thread, long millis) {
622 +        try {
623 +            // No need to optimize the failing case via Thread.join.
624 +            delay(millis);
625 +            assertTrue(thread.isAlive());
626 +        } catch (InterruptedException ie) {
627 +            fail("Unexpected InterruptedException");
628 +        }
629 +    }
630 +
631 +    /**
632 +     * Checks that the threads do not terminate within the default
633 +     * millisecond delay of {@code timeoutMillis()}.
634 +     */
635 +    void assertThreadsStayAlive(Thread... threads) {
636 +        assertThreadsStayAlive(timeoutMillis(), threads);
637 +    }
638 +
639 +    /**
640 +     * Checks that the threads do not terminate within the given millisecond delay.
641 +     */
642 +    void assertThreadsStayAlive(long millis, Thread... threads) {
643 +        try {
644 +            // No need to optimize the failing case via Thread.join.
645 +            delay(millis);
646 +            for (Thread thread : threads)
647 +                assertTrue(thread.isAlive());
648 +        } catch (InterruptedException ie) {
649 +            fail("Unexpected InterruptedException");
650 +        }
651 +    }
652 +
653 +    /**
654 +     * Checks that future.get times out, with the default timeout of
655 +     * {@code timeoutMillis()}.
656 +     */
657 +    void assertFutureTimesOut(Future future) {
658 +        assertFutureTimesOut(future, timeoutMillis());
659 +    }
660 +
661 +    /**
662 +     * Checks that future.get times out, with the given millisecond timeout.
663 +     */
664 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
665 +        long startTime = System.nanoTime();
666 +        try {
667 +            future.get(timeoutMillis, MILLISECONDS);
668 +            shouldThrow();
669 +        } catch (TimeoutException success) {
670 +        } catch (Exception e) {
671 +            threadUnexpectedException(e);
672 +        } finally { future.cancel(true); }
673 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
674 +    }
675  
676      /**
677       * Fails with message "should throw exception".
# Line 497 | Line 712 | public class JSR166TestCase extends Test
712      public static final Integer m6  = new Integer(-6);
713      public static final Integer m10 = new Integer(-10);
714  
500
715      /**
716       * Runs Runnable r with a security policy that permits precisely
717       * the specified permissions.  If there is no current security
# Line 509 | Line 723 | public class JSR166TestCase extends Test
723          SecurityManager sm = System.getSecurityManager();
724          if (sm == null) {
725              r.run();
726 +        }
727 +        runWithSecurityManagerWithPermissions(r, permissions);
728 +    }
729 +
730 +    /**
731 +     * Runs Runnable r with a security policy that permits precisely
732 +     * the specified permissions.  If there is no current security
733 +     * manager, a temporary one is set for the duration of the
734 +     * Runnable.  We require that any security manager permit
735 +     * getPolicy/setPolicy.
736 +     */
737 +    public void runWithSecurityManagerWithPermissions(Runnable r,
738 +                                                      Permission... permissions) {
739 +        SecurityManager sm = System.getSecurityManager();
740 +        if (sm == null) {
741              Policy savedPolicy = Policy.getPolicy();
742              try {
743                  Policy.setPolicy(permissivePolicy());
744                  System.setSecurityManager(new SecurityManager());
745 <                runWithPermissions(r, permissions);
745 >                runWithSecurityManagerWithPermissions(r, permissions);
746              } finally {
747                  System.setSecurityManager(null);
748                  Policy.setPolicy(savedPolicy);
# Line 561 | Line 790 | public class JSR166TestCase extends Test
790              return perms.implies(p);
791          }
792          public void refresh() {}
793 +        public String toString() {
794 +            List<Permission> ps = new ArrayList<Permission>();
795 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
796 +                ps.add(e.nextElement());
797 +            return "AdjustablePolicy with permissions " + ps;
798 +        }
799      }
800  
801      /**
# Line 588 | Line 823 | public class JSR166TestCase extends Test
823       */
824      void sleep(long millis) {
825          try {
826 <            Thread.sleep(millis);
826 >            delay(millis);
827          } catch (InterruptedException ie) {
828              AssertionFailedError afe =
829                  new AssertionFailedError("Unexpected InterruptedException");
# Line 598 | Line 833 | public class JSR166TestCase extends Test
833      }
834  
835      /**
836 <     * Sleeps until the timeout has elapsed, or interrupted.
602 <     * Does <em>NOT</em> throw InterruptedException.
603 <     */
604 <    void sleepTillInterrupted(long timeoutMillis) {
605 <        try {
606 <            Thread.sleep(timeoutMillis);
607 <        } catch (InterruptedException wakeup) {}
608 <    }
609 <
610 <    /**
611 <     * Waits up to the specified number of milliseconds for the given
836 >     * Spin-waits up to the specified number of milliseconds for the given
837       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
838       */
839      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
840 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
616 <        long t0 = System.nanoTime();
840 >        long startTime = System.nanoTime();
841          for (;;) {
842              Thread.State s = thread.getState();
843              if (s == Thread.State.BLOCKED ||
# Line 622 | Line 846 | public class JSR166TestCase extends Test
846                  return;
847              else if (s == Thread.State.TERMINATED)
848                  fail("Unexpected thread termination");
849 <            else if (System.nanoTime() - t0 > timeoutNanos) {
849 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
850                  threadAssertTrue(thread.isAlive());
851                  return;
852              }
# Line 668 | Line 892 | public class JSR166TestCase extends Test
892          } catch (InterruptedException ie) {
893              threadUnexpectedException(ie);
894          } finally {
895 <            if (t.isAlive()) {
895 >            if (t.getState() != Thread.State.TERMINATED) {
896                  t.interrupt();
897                  fail("Test timed out");
898              }
# Line 746 | Line 970 | public class JSR166TestCase extends Test
970                  realRun();
971                  threadShouldThrow("InterruptedException");
972              } catch (InterruptedException success) {
973 +                threadAssertFalse(Thread.interrupted());
974              } catch (Throwable t) {
975                  threadUnexpectedException(t);
976              }
# Line 775 | Line 1000 | public class JSR166TestCase extends Test
1000                  threadShouldThrow("InterruptedException");
1001                  return result;
1002              } catch (InterruptedException success) {
1003 +                threadAssertFalse(Thread.interrupted());
1004              } catch (Throwable t) {
1005                  threadUnexpectedException(t);
1006              }
# Line 809 | Line 1035 | public class JSR166TestCase extends Test
1035      public Runnable awaiter(final CountDownLatch latch) {
1036          return new CheckedRunnable() {
1037              public void realRun() throws InterruptedException {
1038 <                latch.await();
1038 >                await(latch);
1039              }};
1040      }
1041  
1042 +    public void await(CountDownLatch latch) {
1043 +        try {
1044 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1045 +        } catch (Throwable t) {
1046 +            threadUnexpectedException(t);
1047 +        }
1048 +    }
1049 +
1050 +    public void await(Semaphore semaphore) {
1051 +        try {
1052 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1053 +        } catch (Throwable t) {
1054 +            threadUnexpectedException(t);
1055 +        }
1056 +    }
1057 +
1058 + //     /**
1059 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1060 + //      */
1061 + //     public void await(AtomicBoolean flag) {
1062 + //         await(flag, LONG_DELAY_MS);
1063 + //     }
1064 +
1065 + //     /**
1066 + //      * Spin-waits up to the specified timeout until flag becomes true.
1067 + //      */
1068 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1069 + //         long startTime = System.nanoTime();
1070 + //         while (!flag.get()) {
1071 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1072 + //                 throw new AssertionFailedError("timed out");
1073 + //             Thread.yield();
1074 + //         }
1075 + //     }
1076 +
1077      public static class NPETask implements Callable<String> {
1078          public String call() { throw new NullPointerException(); }
1079      }
# Line 823 | Line 1084 | public class JSR166TestCase extends Test
1084  
1085      public class ShortRunnable extends CheckedRunnable {
1086          protected void realRun() throws Throwable {
1087 <            Thread.sleep(SHORT_DELAY_MS);
1087 >            delay(SHORT_DELAY_MS);
1088          }
1089      }
1090  
1091      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1092          protected void realRun() throws InterruptedException {
1093 <            Thread.sleep(SHORT_DELAY_MS);
1093 >            delay(SHORT_DELAY_MS);
1094          }
1095      }
1096  
1097      public class SmallRunnable extends CheckedRunnable {
1098          protected void realRun() throws Throwable {
1099 <            Thread.sleep(SMALL_DELAY_MS);
1099 >            delay(SMALL_DELAY_MS);
1100          }
1101      }
1102  
1103      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1104          protected void realRun() {
1105              try {
1106 <                Thread.sleep(SMALL_DELAY_MS);
1106 >                delay(SMALL_DELAY_MS);
1107              } catch (InterruptedException ok) {}
1108          }
1109      }
1110  
1111      public class SmallCallable extends CheckedCallable {
1112          protected Object realCall() throws InterruptedException {
1113 <            Thread.sleep(SMALL_DELAY_MS);
1113 >            delay(SMALL_DELAY_MS);
1114              return Boolean.TRUE;
1115          }
1116      }
1117  
1118      public class MediumRunnable extends CheckedRunnable {
1119          protected void realRun() throws Throwable {
1120 <            Thread.sleep(MEDIUM_DELAY_MS);
1120 >            delay(MEDIUM_DELAY_MS);
1121          }
1122      }
1123  
1124      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1125          protected void realRun() throws InterruptedException {
1126 <            Thread.sleep(MEDIUM_DELAY_MS);
1126 >            delay(MEDIUM_DELAY_MS);
1127          }
1128      }
1129  
# Line 870 | Line 1131 | public class JSR166TestCase extends Test
1131          return new CheckedRunnable() {
1132              protected void realRun() {
1133                  try {
1134 <                    Thread.sleep(timeoutMillis);
1134 >                    delay(timeoutMillis);
1135                  } catch (InterruptedException ok) {}
1136              }};
1137      }
# Line 878 | Line 1139 | public class JSR166TestCase extends Test
1139      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1140          protected void realRun() {
1141              try {
1142 <                Thread.sleep(MEDIUM_DELAY_MS);
1142 >                delay(MEDIUM_DELAY_MS);
1143              } catch (InterruptedException ok) {}
1144          }
1145      }
# Line 886 | Line 1147 | public class JSR166TestCase extends Test
1147      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1148          protected void realRun() {
1149              try {
1150 <                Thread.sleep(LONG_DELAY_MS);
1150 >                delay(LONG_DELAY_MS);
1151              } catch (InterruptedException ok) {}
1152          }
1153      }
# Line 910 | Line 1171 | public class JSR166TestCase extends Test
1171                  public boolean isDone() { return done; }
1172                  public void run() {
1173                      try {
1174 <                        Thread.sleep(timeoutMillis);
1174 >                        delay(timeoutMillis);
1175                          done = true;
1176                      } catch (InterruptedException ok) {}
1177                  }
# Line 921 | Line 1182 | public class JSR166TestCase extends Test
1182          public volatile boolean done = false;
1183          public void run() {
1184              try {
1185 <                Thread.sleep(SHORT_DELAY_MS);
1185 >                delay(SHORT_DELAY_MS);
1186                  done = true;
1187              } catch (InterruptedException ok) {}
1188          }
# Line 931 | Line 1192 | public class JSR166TestCase extends Test
1192          public volatile boolean done = false;
1193          public void run() {
1194              try {
1195 <                Thread.sleep(SMALL_DELAY_MS);
1195 >                delay(SMALL_DELAY_MS);
1196                  done = true;
1197              } catch (InterruptedException ok) {}
1198          }
# Line 941 | Line 1202 | public class JSR166TestCase extends Test
1202          public volatile boolean done = false;
1203          public void run() {
1204              try {
1205 <                Thread.sleep(MEDIUM_DELAY_MS);
1205 >                delay(MEDIUM_DELAY_MS);
1206                  done = true;
1207              } catch (InterruptedException ok) {}
1208          }
# Line 951 | Line 1212 | public class JSR166TestCase extends Test
1212          public volatile boolean done = false;
1213          public void run() {
1214              try {
1215 <                Thread.sleep(LONG_DELAY_MS);
1215 >                delay(LONG_DELAY_MS);
1216                  done = true;
1217              } catch (InterruptedException ok) {}
1218          }
# Line 968 | Line 1229 | public class JSR166TestCase extends Test
1229          public volatile boolean done = false;
1230          public Object call() {
1231              try {
1232 <                Thread.sleep(SMALL_DELAY_MS);
1232 >                delay(SMALL_DELAY_MS);
1233                  done = true;
1234              } catch (InterruptedException ok) {}
1235              return Boolean.TRUE;
# Line 981 | Line 1242 | public class JSR166TestCase extends Test
1242      public abstract class CheckedRecursiveAction extends RecursiveAction {
1243          protected abstract void realCompute() throws Throwable;
1244  
1245 <        public final void compute() {
1245 >        @Override protected final void compute() {
1246              try {
1247                  realCompute();
1248              } catch (Throwable t) {
# Line 996 | Line 1257 | public class JSR166TestCase extends Test
1257      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1258          protected abstract T realCompute() throws Throwable;
1259  
1260 <        public final T compute() {
1260 >        @Override protected final T compute() {
1261              try {
1262                  return realCompute();
1263              } catch (Throwable t) {
# Line 1015 | Line 1276 | public class JSR166TestCase extends Test
1276      }
1277  
1278      /**
1279 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1280 <     * of throwing checked exceptions.
1279 >     * A CyclicBarrier that uses timed await and fails with
1280 >     * AssertionFailedErrors instead of throwing checked exceptions.
1281       */
1282      public class CheckedBarrier extends CyclicBarrier {
1283          public CheckedBarrier(int parties) { super(parties); }
1284  
1285          public int await() {
1286              try {
1287 <                return super.await();
1287 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1288 >            } catch (TimeoutException e) {
1289 >                throw new AssertionFailedError("timed out");
1290              } catch (Exception e) {
1291                  AssertionFailedError afe =
1292                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1033 | Line 1296 | public class JSR166TestCase extends Test
1296          }
1297      }
1298  
1299 <    public void checkEmpty(BlockingQueue q) {
1299 >    void checkEmpty(BlockingQueue q) {
1300          try {
1301              assertTrue(q.isEmpty());
1302              assertEquals(0, q.size());
# Line 1060 | Line 1323 | public class JSR166TestCase extends Test
1323          }
1324      }
1325  
1326 +    void assertSerialEquals(Object x, Object y) {
1327 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1328 +    }
1329 +
1330 +    void assertNotSerialEquals(Object x, Object y) {
1331 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1332 +    }
1333 +
1334 +    byte[] serialBytes(Object o) {
1335 +        try {
1336 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1337 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1338 +            oos.writeObject(o);
1339 +            oos.flush();
1340 +            oos.close();
1341 +            return bos.toByteArray();
1342 +        } catch (Throwable t) {
1343 +            threadUnexpectedException(t);
1344 +            return new byte[0];
1345 +        }
1346 +    }
1347 +
1348 +    @SuppressWarnings("unchecked")
1349 +    <T> T serialClone(T o) {
1350 +        try {
1351 +            ObjectInputStream ois = new ObjectInputStream
1352 +                (new ByteArrayInputStream(serialBytes(o)));
1353 +            T clone = (T) ois.readObject();
1354 +            assertSame(o.getClass(), clone.getClass());
1355 +            return clone;
1356 +        } catch (Throwable t) {
1357 +            threadUnexpectedException(t);
1358 +            return null;
1359 +        }
1360 +    }
1361 +
1362 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1363 +                             Runnable... throwingActions) {
1364 +        for (Runnable throwingAction : throwingActions) {
1365 +            boolean threw = false;
1366 +            try { throwingAction.run(); }
1367 +            catch (Throwable t) {
1368 +                threw = true;
1369 +                if (!expectedExceptionClass.isInstance(t)) {
1370 +                    AssertionFailedError afe =
1371 +                        new AssertionFailedError
1372 +                        ("Expected " + expectedExceptionClass.getName() +
1373 +                         ", got " + t.getClass().getName());
1374 +                    afe.initCause(t);
1375 +                    threadUnexpectedException(afe);
1376 +                }
1377 +            }
1378 +            if (!threw)
1379 +                shouldThrow(expectedExceptionClass.getName());
1380 +        }
1381 +    }
1382   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines