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.62 by jsr166, Mon Oct 11 05:40:41 2010 UTC vs.
Revision 1.110 by jsr166, Sun Jul 14 22:39:31 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 113 | 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 131 | 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 165 | 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 234 | 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 +                "LongAccumulatorTest",
304 +                "LongAdderTest",
305 +                "SplittableRandomTest",
306 +                "StampedLockTest",
307 +            };
308 +            addNamedTestClasses(suite, java8TestClassNames);
309 +        }
310 +
311 +        return suite;
312      }
313  
314 +    // Delays for timing-dependent tests, in milliseconds.
315  
316      public static long SHORT_DELAY_MS;
317      public static long SMALL_DELAY_MS;
318      public static long MEDIUM_DELAY_MS;
319      public static long LONG_DELAY_MS;
320  
245
321      /**
322       * Returns the shortest timed delay. This could
323       * be reimplemented to use for example a Property.
# Line 251 | Line 326 | public class JSR166TestCase extends Test
326          return 50;
327      }
328  
254
329      /**
330       * Sets delays as multiples of SHORT_DELAY.
331       */
# Line 259 | Line 333 | public class JSR166TestCase extends Test
333          SHORT_DELAY_MS = getShortDelay();
334          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
335          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
336 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
336 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
337 >    }
338 >
339 >    /**
340 >     * Returns a timeout in milliseconds to be used in tests that
341 >     * verify that operations block or time out.
342 >     */
343 >    long timeoutMillis() {
344 >        return SHORT_DELAY_MS / 4;
345 >    }
346 >
347 >    /**
348 >     * Returns a new Date instance representing a time delayMillis
349 >     * milliseconds in the future.
350 >     */
351 >    Date delayedDate(long delayMillis) {
352 >        return new Date(System.currentTimeMillis() + delayMillis);
353      }
354  
355      /**
# Line 283 | Line 373 | public class JSR166TestCase extends Test
373      }
374  
375      /**
376 +     * Extra checks that get done for all test cases.
377 +     *
378       * Triggers test case failure if any thread assertions have failed,
379       * by rethrowing, in the test harness thread, any exception recorded
380       * earlier by threadRecordFailure.
381 +     *
382 +     * Triggers test case failure if interrupt status is set in the main thread.
383       */
384      public void tearDown() throws Exception {
385 <        Throwable t = threadFailure.get();
385 >        Throwable t = threadFailure.getAndSet(null);
386          if (t != null) {
387              if (t instanceof Error)
388                  throw (Error) t;
# Line 303 | Line 397 | public class JSR166TestCase extends Test
397                  throw afe;
398              }
399          }
400 +
401 +        if (Thread.interrupted())
402 +            throw new AssertionFailedError("interrupt status set in main thread");
403 +
404 +        checkForkJoinPoolThreadLeaks();
405 +    }
406 +
407 +    /**
408 +     * Find missing try { ... } finally { joinPool(e); }
409 +     */
410 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
411 +        Thread[] survivors = new Thread[5];
412 +        int count = Thread.enumerate(survivors);
413 +        for (int i = 0; i < count; i++) {
414 +            Thread thread = survivors[i];
415 +            String name = thread.getName();
416 +            if (name.startsWith("ForkJoinPool-")) {
417 +                // give thread some time to terminate
418 +                thread.join(LONG_DELAY_MS);
419 +                if (!thread.isAlive()) continue;
420 +                thread.stop();
421 +                throw new AssertionFailedError
422 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
423 +                                   toString(), name));
424 +            }
425 +        }
426      }
427  
428      /**
# Line 434 | Line 554 | public class JSR166TestCase extends Test
554          else {
555              AssertionFailedError afe =
556                  new AssertionFailedError("unexpected exception: " + t);
557 <            t.initCause(t);
557 >            afe.initCause(t);
558              throw afe;
559          }
560      }
561  
562      /**
563 +     * Delays, via Thread.sleep, for the given millisecond delay, but
564 +     * if the sleep is shorter than specified, may re-sleep or yield
565 +     * until time elapses.
566 +     */
567 +    static void delay(long millis) throws InterruptedException {
568 +        long startTime = System.nanoTime();
569 +        long ns = millis * 1000 * 1000;
570 +        for (;;) {
571 +            if (millis > 0L)
572 +                Thread.sleep(millis);
573 +            else // too short to sleep
574 +                Thread.yield();
575 +            long d = ns - (System.nanoTime() - startTime);
576 +            if (d > 0L)
577 +                millis = d / (1000 * 1000);
578 +            else
579 +                break;
580 +        }
581 +    }
582 +
583 +    /**
584       * Waits out termination of a thread pool or fails doing so.
585       */
586 <    public void joinPool(ExecutorService exec) {
586 >    void joinPool(ExecutorService exec) {
587          try {
588              exec.shutdown();
589              assertTrue("ExecutorService did not terminate in a timely manner",
590 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
590 >                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
591          } catch (SecurityException ok) {
592              // Allowed in case test doesn't have privs
593          } catch (InterruptedException ie) {
# Line 454 | Line 595 | public class JSR166TestCase extends Test
595          }
596      }
597  
598 +    /**
599 +     * A debugging tool to print all stack traces, as jstack does.
600 +     */
601 +    static void printAllStackTraces() {
602 +        for (ThreadInfo info :
603 +                 ManagementFactory.getThreadMXBean()
604 +                 .dumpAllThreads(true, true))
605 +            System.err.print(info);
606 +    }
607 +
608 +    /**
609 +     * Checks that thread does not terminate within the default
610 +     * millisecond delay of {@code timeoutMillis()}.
611 +     */
612 +    void assertThreadStaysAlive(Thread thread) {
613 +        assertThreadStaysAlive(thread, timeoutMillis());
614 +    }
615 +
616 +    /**
617 +     * Checks that thread does not terminate within the given millisecond delay.
618 +     */
619 +    void assertThreadStaysAlive(Thread thread, long millis) {
620 +        try {
621 +            // No need to optimize the failing case via Thread.join.
622 +            delay(millis);
623 +            assertTrue(thread.isAlive());
624 +        } catch (InterruptedException ie) {
625 +            fail("Unexpected InterruptedException");
626 +        }
627 +    }
628 +
629 +    /**
630 +     * Checks that the threads do not terminate within the default
631 +     * millisecond delay of {@code timeoutMillis()}.
632 +     */
633 +    void assertThreadsStayAlive(Thread... threads) {
634 +        assertThreadsStayAlive(timeoutMillis(), threads);
635 +    }
636 +
637 +    /**
638 +     * Checks that the threads do not terminate within the given millisecond delay.
639 +     */
640 +    void assertThreadsStayAlive(long millis, Thread... threads) {
641 +        try {
642 +            // No need to optimize the failing case via Thread.join.
643 +            delay(millis);
644 +            for (Thread thread : threads)
645 +                assertTrue(thread.isAlive());
646 +        } catch (InterruptedException ie) {
647 +            fail("Unexpected InterruptedException");
648 +        }
649 +    }
650 +
651 +    /**
652 +     * Checks that future.get times out, with the default timeout of
653 +     * {@code timeoutMillis()}.
654 +     */
655 +    void assertFutureTimesOut(Future future) {
656 +        assertFutureTimesOut(future, timeoutMillis());
657 +    }
658 +
659 +    /**
660 +     * Checks that future.get times out, with the given millisecond timeout.
661 +     */
662 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
663 +        long startTime = System.nanoTime();
664 +        try {
665 +            future.get(timeoutMillis, MILLISECONDS);
666 +            shouldThrow();
667 +        } catch (TimeoutException success) {
668 +        } catch (Exception e) {
669 +            threadUnexpectedException(e);
670 +        } finally { future.cancel(true); }
671 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
672 +    }
673  
674      /**
675       * Fails with message "should throw exception".
# Line 494 | Line 710 | public class JSR166TestCase extends Test
710      public static final Integer m6  = new Integer(-6);
711      public static final Integer m10 = new Integer(-10);
712  
497
713      /**
714       * Runs Runnable r with a security policy that permits precisely
715       * the specified permissions.  If there is no current security
# Line 506 | Line 721 | public class JSR166TestCase extends Test
721          SecurityManager sm = System.getSecurityManager();
722          if (sm == null) {
723              r.run();
724 +        }
725 +        runWithSecurityManagerWithPermissions(r, permissions);
726 +    }
727 +
728 +    /**
729 +     * Runs Runnable r with a security policy that permits precisely
730 +     * the specified permissions.  If there is no current security
731 +     * manager, a temporary one is set for the duration of the
732 +     * Runnable.  We require that any security manager permit
733 +     * getPolicy/setPolicy.
734 +     */
735 +    public void runWithSecurityManagerWithPermissions(Runnable r,
736 +                                                      Permission... permissions) {
737 +        SecurityManager sm = System.getSecurityManager();
738 +        if (sm == null) {
739              Policy savedPolicy = Policy.getPolicy();
740              try {
741                  Policy.setPolicy(permissivePolicy());
742                  System.setSecurityManager(new SecurityManager());
743 <                runWithPermissions(r, permissions);
743 >                runWithSecurityManagerWithPermissions(r, permissions);
744              } finally {
745                  System.setSecurityManager(null);
746                  Policy.setPolicy(savedPolicy);
# Line 558 | Line 788 | public class JSR166TestCase extends Test
788              return perms.implies(p);
789          }
790          public void refresh() {}
791 +        public String toString() {
792 +            List<Permission> ps = new ArrayList<Permission>();
793 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
794 +                ps.add(e.nextElement());
795 +            return "AdjustablePolicy with permissions " + ps;
796 +        }
797      }
798  
799      /**
# Line 585 | Line 821 | public class JSR166TestCase extends Test
821       */
822      void sleep(long millis) {
823          try {
824 <            Thread.sleep(millis);
824 >            delay(millis);
825          } catch (InterruptedException ie) {
826              AssertionFailedError afe =
827                  new AssertionFailedError("Unexpected InterruptedException");
# Line 595 | Line 831 | public class JSR166TestCase extends Test
831      }
832  
833      /**
834 <     * Sleeps until the timeout has elapsed, or interrupted.
835 <     * Does <em>NOT</em> throw InterruptedException.
834 >     * Spin-waits up to the specified number of milliseconds for the given
835 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
836       */
837 <    void sleepTillInterrupted(long timeoutMillis) {
838 <        try {
839 <            Thread.sleep(timeoutMillis);
840 <        } catch (InterruptedException wakeup) {}
837 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
838 >        long startTime = System.nanoTime();
839 >        for (;;) {
840 >            Thread.State s = thread.getState();
841 >            if (s == Thread.State.BLOCKED ||
842 >                s == Thread.State.WAITING ||
843 >                s == Thread.State.TIMED_WAITING)
844 >                return;
845 >            else if (s == Thread.State.TERMINATED)
846 >                fail("Unexpected thread termination");
847 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
848 >                threadAssertTrue(thread.isAlive());
849 >                return;
850 >            }
851 >            Thread.yield();
852 >        }
853 >    }
854 >
855 >    /**
856 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
857 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
858 >     */
859 >    void waitForThreadToEnterWaitState(Thread thread) {
860 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
861 >    }
862 >
863 >    /**
864 >     * Returns the number of milliseconds since time given by
865 >     * startNanoTime, which must have been previously returned from a
866 >     * call to {@link System.nanoTime()}.
867 >     */
868 >    long millisElapsedSince(long startNanoTime) {
869 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
870      }
871  
872      /**
# Line 625 | Line 890 | public class JSR166TestCase extends Test
890          } catch (InterruptedException ie) {
891              threadUnexpectedException(ie);
892          } finally {
893 <            if (t.isAlive()) {
893 >            if (t.getState() != Thread.State.TERMINATED) {
894                  t.interrupt();
895                  fail("Test timed out");
896              }
897          }
898      }
899  
900 +    /**
901 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
902 +     * terminate (using {@link Thread#join(long)}), else interrupts
903 +     * the thread (in the hope that it may terminate later) and fails.
904 +     */
905 +    void awaitTermination(Thread t) {
906 +        awaitTermination(t, LONG_DELAY_MS);
907 +    }
908 +
909      // Some convenient Runnable classes
910  
911      public abstract class CheckedRunnable implements Runnable {
# Line 694 | Line 968 | public class JSR166TestCase extends Test
968                  realRun();
969                  threadShouldThrow("InterruptedException");
970              } catch (InterruptedException success) {
971 +                threadAssertFalse(Thread.interrupted());
972              } catch (Throwable t) {
973                  threadUnexpectedException(t);
974              }
# Line 723 | Line 998 | public class JSR166TestCase extends Test
998                  threadShouldThrow("InterruptedException");
999                  return result;
1000              } catch (InterruptedException success) {
1001 +                threadAssertFalse(Thread.interrupted());
1002              } catch (Throwable t) {
1003                  threadUnexpectedException(t);
1004              }
# Line 746 | Line 1022 | public class JSR166TestCase extends Test
1022  
1023      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1024          return new CheckedCallable<String>() {
1025 <            public String realCall() {
1025 >            protected String realCall() {
1026                  try {
1027                      latch.await();
1028                  } catch (InterruptedException quittingTime) {}
# Line 754 | Line 1030 | public class JSR166TestCase extends Test
1030              }};
1031      }
1032  
1033 +    public Runnable awaiter(final CountDownLatch latch) {
1034 +        return new CheckedRunnable() {
1035 +            public void realRun() throws InterruptedException {
1036 +                await(latch);
1037 +            }};
1038 +    }
1039 +
1040 +    public void await(CountDownLatch latch) {
1041 +        try {
1042 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1043 +        } catch (Throwable t) {
1044 +            threadUnexpectedException(t);
1045 +        }
1046 +    }
1047 +
1048 +    public void await(Semaphore semaphore) {
1049 +        try {
1050 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1051 +        } catch (Throwable t) {
1052 +            threadUnexpectedException(t);
1053 +        }
1054 +    }
1055 +
1056 + //     /**
1057 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1058 + //      */
1059 + //     public void await(AtomicBoolean flag) {
1060 + //         await(flag, LONG_DELAY_MS);
1061 + //     }
1062 +
1063 + //     /**
1064 + //      * Spin-waits up to the specified timeout until flag becomes true.
1065 + //      */
1066 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1067 + //         long startTime = System.nanoTime();
1068 + //         while (!flag.get()) {
1069 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1070 + //                 throw new AssertionFailedError("timed out");
1071 + //             Thread.yield();
1072 + //         }
1073 + //     }
1074 +
1075      public static class NPETask implements Callable<String> {
1076          public String call() { throw new NullPointerException(); }
1077      }
# Line 764 | Line 1082 | public class JSR166TestCase extends Test
1082  
1083      public class ShortRunnable extends CheckedRunnable {
1084          protected void realRun() throws Throwable {
1085 <            Thread.sleep(SHORT_DELAY_MS);
1085 >            delay(SHORT_DELAY_MS);
1086          }
1087      }
1088  
1089      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1090          protected void realRun() throws InterruptedException {
1091 <            Thread.sleep(SHORT_DELAY_MS);
1091 >            delay(SHORT_DELAY_MS);
1092          }
1093      }
1094  
1095      public class SmallRunnable extends CheckedRunnable {
1096          protected void realRun() throws Throwable {
1097 <            Thread.sleep(SMALL_DELAY_MS);
1097 >            delay(SMALL_DELAY_MS);
1098          }
1099      }
1100  
1101      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1102          protected void realRun() {
1103              try {
1104 <                Thread.sleep(SMALL_DELAY_MS);
1104 >                delay(SMALL_DELAY_MS);
1105              } catch (InterruptedException ok) {}
1106          }
1107      }
1108  
1109      public class SmallCallable extends CheckedCallable {
1110          protected Object realCall() throws InterruptedException {
1111 <            Thread.sleep(SMALL_DELAY_MS);
1111 >            delay(SMALL_DELAY_MS);
1112              return Boolean.TRUE;
1113          }
1114      }
1115  
1116      public class MediumRunnable extends CheckedRunnable {
1117          protected void realRun() throws Throwable {
1118 <            Thread.sleep(MEDIUM_DELAY_MS);
1118 >            delay(MEDIUM_DELAY_MS);
1119          }
1120      }
1121  
1122      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1123          protected void realRun() throws InterruptedException {
1124 <            Thread.sleep(MEDIUM_DELAY_MS);
1124 >            delay(MEDIUM_DELAY_MS);
1125          }
1126      }
1127  
1128 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1129 +        return new CheckedRunnable() {
1130 +            protected void realRun() {
1131 +                try {
1132 +                    delay(timeoutMillis);
1133 +                } catch (InterruptedException ok) {}
1134 +            }};
1135 +    }
1136 +
1137      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1138          protected void realRun() {
1139              try {
1140 <                Thread.sleep(MEDIUM_DELAY_MS);
1140 >                delay(MEDIUM_DELAY_MS);
1141              } catch (InterruptedException ok) {}
1142          }
1143      }
# Line 818 | Line 1145 | public class JSR166TestCase extends Test
1145      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1146          protected void realRun() {
1147              try {
1148 <                Thread.sleep(LONG_DELAY_MS);
1148 >                delay(LONG_DELAY_MS);
1149              } catch (InterruptedException ok) {}
1150          }
1151      }
# Line 842 | Line 1169 | public class JSR166TestCase extends Test
1169                  public boolean isDone() { return done; }
1170                  public void run() {
1171                      try {
1172 <                        Thread.sleep(timeoutMillis);
1172 >                        delay(timeoutMillis);
1173                          done = true;
1174                      } catch (InterruptedException ok) {}
1175                  }
# Line 853 | Line 1180 | public class JSR166TestCase extends Test
1180          public volatile boolean done = false;
1181          public void run() {
1182              try {
1183 <                Thread.sleep(SHORT_DELAY_MS);
1183 >                delay(SHORT_DELAY_MS);
1184                  done = true;
1185              } catch (InterruptedException ok) {}
1186          }
# Line 863 | Line 1190 | public class JSR166TestCase extends Test
1190          public volatile boolean done = false;
1191          public void run() {
1192              try {
1193 <                Thread.sleep(SMALL_DELAY_MS);
1193 >                delay(SMALL_DELAY_MS);
1194                  done = true;
1195              } catch (InterruptedException ok) {}
1196          }
# Line 873 | Line 1200 | public class JSR166TestCase extends Test
1200          public volatile boolean done = false;
1201          public void run() {
1202              try {
1203 <                Thread.sleep(MEDIUM_DELAY_MS);
1203 >                delay(MEDIUM_DELAY_MS);
1204                  done = true;
1205              } catch (InterruptedException ok) {}
1206          }
# Line 883 | Line 1210 | public class JSR166TestCase extends Test
1210          public volatile boolean done = false;
1211          public void run() {
1212              try {
1213 <                Thread.sleep(LONG_DELAY_MS);
1213 >                delay(LONG_DELAY_MS);
1214                  done = true;
1215              } catch (InterruptedException ok) {}
1216          }
# Line 900 | Line 1227 | public class JSR166TestCase extends Test
1227          public volatile boolean done = false;
1228          public Object call() {
1229              try {
1230 <                Thread.sleep(SMALL_DELAY_MS);
1230 >                delay(SMALL_DELAY_MS);
1231                  done = true;
1232              } catch (InterruptedException ok) {}
1233              return Boolean.TRUE;
# Line 913 | Line 1240 | public class JSR166TestCase extends Test
1240      public abstract class CheckedRecursiveAction extends RecursiveAction {
1241          protected abstract void realCompute() throws Throwable;
1242  
1243 <        public final void compute() {
1243 >        @Override protected final void compute() {
1244              try {
1245                  realCompute();
1246              } catch (Throwable t) {
# Line 928 | Line 1255 | public class JSR166TestCase extends Test
1255      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1256          protected abstract T realCompute() throws Throwable;
1257  
1258 <        public final T compute() {
1258 >        @Override protected final T compute() {
1259              try {
1260                  return realCompute();
1261              } catch (Throwable t) {
# Line 947 | Line 1274 | public class JSR166TestCase extends Test
1274      }
1275  
1276      /**
1277 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1278 <     * of throwing checked exceptions.
1277 >     * A CyclicBarrier that uses timed await and fails with
1278 >     * AssertionFailedErrors instead of throwing checked exceptions.
1279       */
1280      public class CheckedBarrier extends CyclicBarrier {
1281          public CheckedBarrier(int parties) { super(parties); }
1282  
1283          public int await() {
1284              try {
1285 <                return super.await();
1285 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1286 >            } catch (TimeoutException e) {
1287 >                throw new AssertionFailedError("timed out");
1288              } catch (Exception e) {
1289                  AssertionFailedError afe =
1290                      new AssertionFailedError("Unexpected exception: " + e);
# Line 965 | Line 1294 | public class JSR166TestCase extends Test
1294          }
1295      }
1296  
1297 +    void checkEmpty(BlockingQueue q) {
1298 +        try {
1299 +            assertTrue(q.isEmpty());
1300 +            assertEquals(0, q.size());
1301 +            assertNull(q.peek());
1302 +            assertNull(q.poll());
1303 +            assertNull(q.poll(0, MILLISECONDS));
1304 +            assertEquals(q.toString(), "[]");
1305 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1306 +            assertFalse(q.iterator().hasNext());
1307 +            try {
1308 +                q.element();
1309 +                shouldThrow();
1310 +            } catch (NoSuchElementException success) {}
1311 +            try {
1312 +                q.iterator().next();
1313 +                shouldThrow();
1314 +            } catch (NoSuchElementException success) {}
1315 +            try {
1316 +                q.remove();
1317 +                shouldThrow();
1318 +            } catch (NoSuchElementException success) {}
1319 +        } catch (InterruptedException ie) {
1320 +            threadUnexpectedException(ie);
1321 +        }
1322 +    }
1323 +
1324 +    void assertSerialEquals(Object x, Object y) {
1325 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1326 +    }
1327 +
1328 +    void assertNotSerialEquals(Object x, Object y) {
1329 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1330 +    }
1331 +
1332 +    byte[] serialBytes(Object o) {
1333 +        try {
1334 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1335 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1336 +            oos.writeObject(o);
1337 +            oos.flush();
1338 +            oos.close();
1339 +            return bos.toByteArray();
1340 +        } catch (Throwable t) {
1341 +            threadUnexpectedException(t);
1342 +            return new byte[0];
1343 +        }
1344 +    }
1345 +
1346 +    @SuppressWarnings("unchecked")
1347 +    <T> T serialClone(T o) {
1348 +        try {
1349 +            ObjectInputStream ois = new ObjectInputStream
1350 +                (new ByteArrayInputStream(serialBytes(o)));
1351 +            T clone = (T) ois.readObject();
1352 +            assertSame(o.getClass(), clone.getClass());
1353 +            return clone;
1354 +        } catch (Throwable t) {
1355 +            threadUnexpectedException(t);
1356 +            return null;
1357 +        }
1358 +    }
1359 +
1360 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1361 +                             Runnable... throwingActions) {
1362 +        for (Runnable throwingAction : throwingActions) {
1363 +            boolean threw = false;
1364 +            try { throwingAction.run(); }
1365 +            catch (Throwable t) {
1366 +                threw = true;
1367 +                if (!expectedExceptionClass.isInstance(t)) {
1368 +                    AssertionFailedError afe =
1369 +                        new AssertionFailedError
1370 +                        ("Expected " + expectedExceptionClass.getName() +
1371 +                         ", got " + t.getClass().getName());
1372 +                    afe.initCause(t);
1373 +                    threadUnexpectedException(afe);
1374 +                }
1375 +            }
1376 +            if (!threw)
1377 +                shouldThrow(expectedExceptionClass.getName());
1378 +        }
1379 +    }
1380   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines