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.80 by jsr166, Fri May 13 21:48:58 2011 UTC vs.
Revision 1.128 by jsr166, Fri Feb 27 22:06:24 2015 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 >
12   import java.io.ByteArrayInputStream;
13   import java.io.ByteArrayOutputStream;
14   import java.io.ObjectInputStream;
15   import java.io.ObjectOutputStream;
16 < import java.util.Arrays;
17 < import java.util.NoSuchElementException;
18 < import java.util.PropertyPermission;
17 < import java.util.concurrent.*;
18 < import java.util.concurrent.atomic.AtomicReference;
19 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
20 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
16 > import java.lang.management.ManagementFactory;
17 > import java.lang.management.ThreadInfo;
18 > import java.lang.reflect.Method;
19   import java.security.CodeSource;
20   import java.security.Permission;
21   import java.security.PermissionCollection;
# Line 25 | Line 23 | import java.security.Permissions;
23   import java.security.Policy;
24   import java.security.ProtectionDomain;
25   import java.security.SecurityPermission;
26 + import java.util.ArrayList;
27 + import java.util.Arrays;
28 + import java.util.Date;
29 + import java.util.Enumeration;
30 + import java.util.Iterator;
31 + import java.util.List;
32 + import java.util.NoSuchElementException;
33 + import java.util.PropertyPermission;
34 + import java.util.concurrent.BlockingQueue;
35 + import java.util.concurrent.Callable;
36 + import java.util.concurrent.CountDownLatch;
37 + import java.util.concurrent.CyclicBarrier;
38 + import java.util.concurrent.ExecutorService;
39 + import java.util.concurrent.Future;
40 + import java.util.concurrent.RecursiveAction;
41 + import java.util.concurrent.RecursiveTask;
42 + import java.util.concurrent.RejectedExecutionHandler;
43 + import java.util.concurrent.Semaphore;
44 + import java.util.concurrent.ThreadFactory;
45 + import java.util.concurrent.ThreadPoolExecutor;
46 + import java.util.concurrent.TimeoutException;
47 + import java.util.concurrent.atomic.AtomicReference;
48 + import java.util.regex.Pattern;
49 +
50 + import junit.framework.AssertionFailedError;
51 + import junit.framework.Test;
52 + import junit.framework.TestCase;
53 + import junit.framework.TestSuite;
54  
55   /**
56   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 67 | Line 93 | import java.security.SecurityPermission;
93   *
94   * </ol>
95   *
96 < * <p> <b>Other notes</b>
96 > * <p><b>Other notes</b>
97   * <ul>
98   *
99   * <li> Usually, there is one testcase method per JSR166 method
# Line 107 | Line 133 | public class JSR166TestCase extends Test
133          Boolean.getBoolean("jsr166.expensiveTests");
134  
135      /**
136 +     * If true, also run tests that are not part of the official tck
137 +     * because they test unspecified implementation details.
138 +     */
139 +    protected static final boolean testImplementationDetails =
140 +        Boolean.getBoolean("jsr166.testImplementationDetails");
141 +
142 +    /**
143       * If true, report on stdout all "slow" tests, that is, ones that
144       * take more than profileThreshold milliseconds to execute.
145       */
# Line 120 | Line 153 | public class JSR166TestCase extends Test
153      private static final long profileThreshold =
154          Long.getLong("jsr166.profileThreshold", 100);
155  
156 +    /**
157 +     * The number of repetitions per test (for tickling rare bugs).
158 +     */
159 +    private static final int runsPerTest =
160 +        Integer.getInteger("jsr166.runsPerTest", 1);
161 +
162 +    /**
163 +     * A filter for tests to run, matching strings of the form
164 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
165 +     * Usefully combined with jsr166.runsPerTest.
166 +     */
167 +    private static final Pattern methodFilter = methodFilter();
168 +
169 +    private static Pattern methodFilter() {
170 +        String regex = System.getProperty("jsr166.methodFilter");
171 +        return (regex == null) ? null : Pattern.compile(regex);
172 +    }
173 +
174      protected void runTest() throws Throwable {
175 <        if (profileTests)
176 <            runTestProfiled();
177 <        else
178 <            super.runTest();
175 >        if (methodFilter == null
176 >            || methodFilter.matcher(toString()).find()) {
177 >            for (int i = 0; i < runsPerTest; i++) {
178 >                if (profileTests)
179 >                    runTestProfiled();
180 >                else
181 >                    super.runTest();
182 >            }
183 >        }
184      }
185  
186      protected void runTestProfiled() throws Throwable {
187 +        // Warmup run, notably to trigger all needed classloading.
188 +        super.runTest();
189          long t0 = System.nanoTime();
190          try {
191              super.runTest();
192          } finally {
193 <            long elapsedMillis =
136 <                (System.nanoTime() - t0) / (1000L * 1000L);
193 >            long elapsedMillis = millisElapsedSince(t0);
194              if (elapsedMillis >= profileThreshold)
195                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
196          }
197      }
198  
199      /**
200 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
200 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
201 >     * Optional command line arg provides the number of iterations to
202 >     * repeat running the tests.
203       */
204      public static void main(String[] args) {
205          if (useSecurityManager) {
# Line 172 | Line 231 | public class JSR166TestCase extends Test
231          return suite;
232      }
233  
234 +    public static void addNamedTestClasses(TestSuite suite,
235 +                                           String... testClassNames) {
236 +        for (String testClassName : testClassNames) {
237 +            try {
238 +                Class<?> testClass = Class.forName(testClassName);
239 +                Method m = testClass.getDeclaredMethod("suite",
240 +                                                       new Class<?>[0]);
241 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
242 +            } catch (Exception e) {
243 +                throw new Error("Missing test class", e);
244 +            }
245 +        }
246 +    }
247 +
248 +    public static final double JAVA_CLASS_VERSION;
249 +    public static final String JAVA_SPECIFICATION_VERSION;
250 +    static {
251 +        try {
252 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
253 +                new java.security.PrivilegedAction<Double>() {
254 +                public Double run() {
255 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
256 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
257 +                new java.security.PrivilegedAction<String>() {
258 +                public String run() {
259 +                    return System.getProperty("java.specification.version");}});
260 +        } catch (Throwable t) {
261 +            throw new Error(t);
262 +        }
263 +    }
264 +
265 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
266 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
267 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
268 +    public static boolean atLeastJava9() {
269 +        // As of 2014-05, java9 still uses 52.0 class file version
270 +        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
271 +    }
272 +
273      /**
274       * Collects all JSR166 unit tests as one suite.
275       */
276      public static Test suite() {
277 <        return newTestSuite(
277 >        // Java7+ test classes
278 >        TestSuite suite = newTestSuite(
279              ForkJoinPoolTest.suite(),
280              ForkJoinTaskTest.suite(),
281              RecursiveActionTest.suite(),
# Line 241 | Line 340 | public class JSR166TestCase extends Test
340              TreeSetTest.suite(),
341              TreeSubMapTest.suite(),
342              TreeSubSetTest.suite());
343 +
344 +        // Java8+ test classes
345 +        if (atLeastJava8()) {
346 +            String[] java8TestClassNames = {
347 +                "Atomic8Test",
348 +                "CompletableFutureTest",
349 +                "ConcurrentHashMap8Test",
350 +                "CountedCompleterTest",
351 +                "DoubleAccumulatorTest",
352 +                "DoubleAdderTest",
353 +                "ForkJoinPool8Test",
354 +                "ForkJoinTask8Test",
355 +                "LongAccumulatorTest",
356 +                "LongAdderTest",
357 +                "SplittableRandomTest",
358 +                "StampedLockTest",
359 +                "ThreadLocalRandom8Test",
360 +            };
361 +            addNamedTestClasses(suite, java8TestClassNames);
362 +        }
363 +
364 +        // Java9+ test classes
365 +        if (atLeastJava9()) {
366 +            String[] java9TestClassNames = {
367 +                "ThreadPoolExecutor9Test",
368 +            };
369 +            addNamedTestClasses(suite, java9TestClassNames);
370 +        }
371 +
372 +        return suite;
373      }
374  
375 +    // Delays for timing-dependent tests, in milliseconds.
376  
377      public static long SHORT_DELAY_MS;
378      public static long SMALL_DELAY_MS;
379      public static long MEDIUM_DELAY_MS;
380      public static long LONG_DELAY_MS;
381  
252
382      /**
383       * Returns the shortest timed delay. This could
384       * be reimplemented to use for example a Property.
# Line 258 | Line 387 | public class JSR166TestCase extends Test
387          return 50;
388      }
389  
261
390      /**
391       * Sets delays as multiples of SHORT_DELAY.
392       */
# Line 270 | Line 398 | public class JSR166TestCase extends Test
398      }
399  
400      /**
401 +     * Returns a timeout in milliseconds to be used in tests that
402 +     * verify that operations block or time out.
403 +     */
404 +    long timeoutMillis() {
405 +        return SHORT_DELAY_MS / 4;
406 +    }
407 +
408 +    /**
409 +     * Returns a new Date instance representing a time delayMillis
410 +     * milliseconds in the future.
411 +     */
412 +    Date delayedDate(long delayMillis) {
413 +        return new Date(System.currentTimeMillis() + delayMillis);
414 +    }
415 +
416 +    /**
417       * The first exception encountered if any threadAssertXXX method fails.
418       */
419      private final AtomicReference<Throwable> threadFailure
# Line 290 | Line 434 | public class JSR166TestCase extends Test
434      }
435  
436      /**
437 +     * Extra checks that get done for all test cases.
438 +     *
439       * Triggers test case failure if any thread assertions have failed,
440       * by rethrowing, in the test harness thread, any exception recorded
441       * earlier by threadRecordFailure.
442 +     *
443 +     * Triggers test case failure if interrupt status is set in the main thread.
444       */
445      public void tearDown() throws Exception {
446          Throwable t = threadFailure.getAndSet(null);
# Line 310 | Line 458 | public class JSR166TestCase extends Test
458                  throw afe;
459              }
460          }
461 +
462 +        if (Thread.interrupted())
463 +            throw new AssertionFailedError("interrupt status set in main thread");
464 +
465 +        checkForkJoinPoolThreadLeaks();
466 +    }
467 +
468 +    /**
469 +     * Finds missing try { ... } finally { joinPool(e); }
470 +     */
471 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
472 +        Thread[] survivors = new Thread[5];
473 +        int count = Thread.enumerate(survivors);
474 +        for (int i = 0; i < count; i++) {
475 +            Thread thread = survivors[i];
476 +            String name = thread.getName();
477 +            if (name.startsWith("ForkJoinPool-")) {
478 +                // give thread some time to terminate
479 +                thread.join(LONG_DELAY_MS);
480 +                if (!thread.isAlive()) continue;
481 +                thread.stop();
482 +                throw new AssertionFailedError
483 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
484 +                                   toString(), name));
485 +            }
486 +        }
487      }
488  
489      /**
# Line 441 | Line 615 | public class JSR166TestCase extends Test
615          else {
616              AssertionFailedError afe =
617                  new AssertionFailedError("unexpected exception: " + t);
618 <            t.initCause(t);
618 >            afe.initCause(t);
619              throw afe;
620          }
621      }
622  
623      /**
624 <     * Delays, via Thread.sleep for the given millisecond delay, but
624 >     * Delays, via Thread.sleep, for the given millisecond delay, but
625       * if the sleep is shorter than specified, may re-sleep or yield
626       * until time elapses.
627       */
628 <    public static void delay(long millis) throws InterruptedException {
628 >    static void delay(long millis) throws InterruptedException {
629          long startTime = System.nanoTime();
630          long ns = millis * 1000 * 1000;
631          for (;;) {
# Line 470 | Line 644 | public class JSR166TestCase extends Test
644      /**
645       * Waits out termination of a thread pool or fails doing so.
646       */
647 <    public void joinPool(ExecutorService exec) {
647 >    void joinPool(ExecutorService exec) {
648          try {
649              exec.shutdown();
650 <            assertTrue("ExecutorService did not terminate in a timely manner",
651 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
650 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
651 >                fail("ExecutorService " + exec +
652 >                     " did not terminate in a timely manner");
653          } catch (SecurityException ok) {
654              // Allowed in case test doesn't have privs
655 <        } catch (InterruptedException ie) {
655 >        } catch (InterruptedException fail) {
656              fail("Unexpected InterruptedException");
657          }
658      }
659  
660      /**
661 +     * A debugging tool to print all stack traces, as jstack does.
662 +     */
663 +    static void printAllStackTraces() {
664 +        for (ThreadInfo info :
665 +                 ManagementFactory.getThreadMXBean()
666 +                 .dumpAllThreads(true, true))
667 +            System.err.print(info);
668 +    }
669 +
670 +    /**
671 +     * Checks that thread does not terminate within the default
672 +     * millisecond delay of {@code timeoutMillis()}.
673 +     */
674 +    void assertThreadStaysAlive(Thread thread) {
675 +        assertThreadStaysAlive(thread, timeoutMillis());
676 +    }
677 +
678 +    /**
679       * Checks that thread does not terminate within the given millisecond delay.
680       */
681 <    public void assertThreadStaysAlive(Thread thread, long millis) {
681 >    void assertThreadStaysAlive(Thread thread, long millis) {
682          try {
683              // No need to optimize the failing case via Thread.join.
684              delay(millis);
685              assertTrue(thread.isAlive());
686 <        } catch (InterruptedException ie) {
686 >        } catch (InterruptedException fail) {
687 >            fail("Unexpected InterruptedException");
688 >        }
689 >    }
690 >
691 >    /**
692 >     * Checks that the threads do not terminate within the default
693 >     * millisecond delay of {@code timeoutMillis()}.
694 >     */
695 >    void assertThreadsStayAlive(Thread... threads) {
696 >        assertThreadsStayAlive(timeoutMillis(), threads);
697 >    }
698 >
699 >    /**
700 >     * Checks that the threads do not terminate within the given millisecond delay.
701 >     */
702 >    void assertThreadsStayAlive(long millis, Thread... threads) {
703 >        try {
704 >            // No need to optimize the failing case via Thread.join.
705 >            delay(millis);
706 >            for (Thread thread : threads)
707 >                assertTrue(thread.isAlive());
708 >        } catch (InterruptedException fail) {
709              fail("Unexpected InterruptedException");
710          }
711      }
712  
713      /**
714 +     * Checks that future.get times out, with the default timeout of
715 +     * {@code timeoutMillis()}.
716 +     */
717 +    void assertFutureTimesOut(Future future) {
718 +        assertFutureTimesOut(future, timeoutMillis());
719 +    }
720 +
721 +    /**
722 +     * Checks that future.get times out, with the given millisecond timeout.
723 +     */
724 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
725 +        long startTime = System.nanoTime();
726 +        try {
727 +            future.get(timeoutMillis, MILLISECONDS);
728 +            shouldThrow();
729 +        } catch (TimeoutException success) {
730 +        } catch (Exception fail) {
731 +            threadUnexpectedException(fail);
732 +        } finally { future.cancel(true); }
733 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
734 +    }
735 +
736 +    /**
737       * Fails with message "should throw exception".
738       */
739      public void shouldThrow() {
# Line 534 | Line 772 | public class JSR166TestCase extends Test
772      public static final Integer m6  = new Integer(-6);
773      public static final Integer m10 = new Integer(-10);
774  
537
775      /**
776       * Runs Runnable r with a security policy that permits precisely
777       * the specified permissions.  If there is no current security
# Line 546 | Line 783 | public class JSR166TestCase extends Test
783          SecurityManager sm = System.getSecurityManager();
784          if (sm == null) {
785              r.run();
786 +        }
787 +        runWithSecurityManagerWithPermissions(r, permissions);
788 +    }
789 +
790 +    /**
791 +     * Runs Runnable r with a security policy that permits precisely
792 +     * the specified permissions.  If there is no current security
793 +     * manager, a temporary one is set for the duration of the
794 +     * Runnable.  We require that any security manager permit
795 +     * getPolicy/setPolicy.
796 +     */
797 +    public void runWithSecurityManagerWithPermissions(Runnable r,
798 +                                                      Permission... permissions) {
799 +        SecurityManager sm = System.getSecurityManager();
800 +        if (sm == null) {
801              Policy savedPolicy = Policy.getPolicy();
802              try {
803                  Policy.setPolicy(permissivePolicy());
804                  System.setSecurityManager(new SecurityManager());
805 <                runWithPermissions(r, permissions);
805 >                runWithSecurityManagerWithPermissions(r, permissions);
806              } finally {
807                  System.setSecurityManager(null);
808                  Policy.setPolicy(savedPolicy);
# Line 598 | Line 850 | public class JSR166TestCase extends Test
850              return perms.implies(p);
851          }
852          public void refresh() {}
853 +        public String toString() {
854 +            List<Permission> ps = new ArrayList<Permission>();
855 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
856 +                ps.add(e.nextElement());
857 +            return "AdjustablePolicy with permissions " + ps;
858 +        }
859      }
860  
861      /**
# Line 626 | Line 884 | public class JSR166TestCase extends Test
884      void sleep(long millis) {
885          try {
886              delay(millis);
887 <        } catch (InterruptedException ie) {
887 >        } catch (InterruptedException fail) {
888              AssertionFailedError afe =
889                  new AssertionFailedError("Unexpected InterruptedException");
890 <            afe.initCause(ie);
890 >            afe.initCause(fail);
891              throw afe;
892          }
893      }
894  
895      /**
896 <     * Sleeps until the timeout has elapsed, or interrupted.
639 <     * Does <em>NOT</em> throw InterruptedException.
640 <     */
641 <    void sleepTillInterrupted(long timeoutMillis) {
642 <        try {
643 <            Thread.sleep(timeoutMillis);
644 <        } catch (InterruptedException wakeup) {}
645 <    }
646 <
647 <    /**
648 <     * Waits up to the specified number of milliseconds for the given
896 >     * Spin-waits up to the specified number of milliseconds for the given
897       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
898       */
899      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
900 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
653 <        long t0 = System.nanoTime();
900 >        long startTime = System.nanoTime();
901          for (;;) {
902              Thread.State s = thread.getState();
903              if (s == Thread.State.BLOCKED ||
# Line 659 | Line 906 | public class JSR166TestCase extends Test
906                  return;
907              else if (s == Thread.State.TERMINATED)
908                  fail("Unexpected thread termination");
909 <            else if (System.nanoTime() - t0 > timeoutNanos) {
909 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
910                  threadAssertTrue(thread.isAlive());
911                  return;
912              }
# Line 678 | Line 925 | public class JSR166TestCase extends Test
925      /**
926       * Returns the number of milliseconds since time given by
927       * startNanoTime, which must have been previously returned from a
928 <     * call to {@link System.nanoTime()}.
928 >     * call to {@link System#nanoTime()}.
929       */
930 <    long millisElapsedSince(long startNanoTime) {
930 >    static long millisElapsedSince(long startNanoTime) {
931          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
932      }
933  
934 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
935 + //         long startTime = System.nanoTime();
936 + //         try {
937 + //             r.run();
938 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
939 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
940 + //             throw new AssertionFailedError("did not return promptly");
941 + //     }
942 +
943 + //     void assertTerminatesPromptly(Runnable r) {
944 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
945 + //     }
946 +
947 +    /**
948 +     * Checks that timed f.get() returns the expected value, and does not
949 +     * wait for the timeout to elapse before returning.
950 +     */
951 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
952 +        long startTime = System.nanoTime();
953 +        try {
954 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
955 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
956 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
957 +            throw new AssertionFailedError("timed get did not return promptly");
958 +    }
959 +
960 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
961 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
962 +    }
963 +
964      /**
965       * Returns a new started daemon Thread running the given runnable.
966       */
# Line 702 | Line 979 | public class JSR166TestCase extends Test
979      void awaitTermination(Thread t, long timeoutMillis) {
980          try {
981              t.join(timeoutMillis);
982 <        } catch (InterruptedException ie) {
983 <            threadUnexpectedException(ie);
982 >        } catch (InterruptedException fail) {
983 >            threadUnexpectedException(fail);
984          } finally {
985 <            if (t.isAlive()) {
985 >            if (t.getState() != Thread.State.TERMINATED) {
986                  t.interrupt();
987                  fail("Test timed out");
988              }
# Line 729 | Line 1006 | public class JSR166TestCase extends Test
1006          public final void run() {
1007              try {
1008                  realRun();
1009 <            } catch (Throwable t) {
1010 <                threadUnexpectedException(t);
1009 >            } catch (Throwable fail) {
1010 >                threadUnexpectedException(fail);
1011              }
1012          }
1013      }
# Line 783 | Line 1060 | public class JSR166TestCase extends Test
1060                  realRun();
1061                  threadShouldThrow("InterruptedException");
1062              } catch (InterruptedException success) {
1063 <            } catch (Throwable t) {
1064 <                threadUnexpectedException(t);
1063 >                threadAssertFalse(Thread.interrupted());
1064 >            } catch (Throwable fail) {
1065 >                threadUnexpectedException(fail);
1066              }
1067          }
1068      }
# Line 795 | Line 1073 | public class JSR166TestCase extends Test
1073          public final T call() {
1074              try {
1075                  return realCall();
1076 <            } catch (Throwable t) {
1077 <                threadUnexpectedException(t);
1076 >            } catch (Throwable fail) {
1077 >                threadUnexpectedException(fail);
1078                  return null;
1079              }
1080          }
# Line 812 | Line 1090 | public class JSR166TestCase extends Test
1090                  threadShouldThrow("InterruptedException");
1091                  return result;
1092              } catch (InterruptedException success) {
1093 <            } catch (Throwable t) {
1094 <                threadUnexpectedException(t);
1093 >                threadAssertFalse(Thread.interrupted());
1094 >            } catch (Throwable fail) {
1095 >                threadUnexpectedException(fail);
1096              }
1097              return null;
1098          }
# Line 853 | Line 1132 | public class JSR166TestCase extends Test
1132      public void await(CountDownLatch latch) {
1133          try {
1134              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1135 <        } catch (Throwable t) {
1136 <            threadUnexpectedException(t);
1135 >        } catch (Throwable fail) {
1136 >            threadUnexpectedException(fail);
1137 >        }
1138 >    }
1139 >
1140 >    public void await(Semaphore semaphore) {
1141 >        try {
1142 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1143 >        } catch (Throwable fail) {
1144 >            threadUnexpectedException(fail);
1145          }
1146      }
1147  
1148 + //     /**
1149 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1150 + //      */
1151 + //     public void await(AtomicBoolean flag) {
1152 + //         await(flag, LONG_DELAY_MS);
1153 + //     }
1154 +
1155 + //     /**
1156 + //      * Spin-waits up to the specified timeout until flag becomes true.
1157 + //      */
1158 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1159 + //         long startTime = System.nanoTime();
1160 + //         while (!flag.get()) {
1161 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1162 + //                 throw new AssertionFailedError("timed out");
1163 + //             Thread.yield();
1164 + //         }
1165 + //     }
1166 +
1167      public static class NPETask implements Callable<String> {
1168          public String call() { throw new NullPointerException(); }
1169      }
# Line 1026 | Line 1332 | public class JSR166TestCase extends Test
1332      public abstract class CheckedRecursiveAction extends RecursiveAction {
1333          protected abstract void realCompute() throws Throwable;
1334  
1335 <        public final void compute() {
1335 >        @Override protected final void compute() {
1336              try {
1337                  realCompute();
1338 <            } catch (Throwable t) {
1339 <                threadUnexpectedException(t);
1338 >            } catch (Throwable fail) {
1339 >                threadUnexpectedException(fail);
1340              }
1341          }
1342      }
# Line 1041 | Line 1347 | public class JSR166TestCase extends Test
1347      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1348          protected abstract T realCompute() throws Throwable;
1349  
1350 <        public final T compute() {
1350 >        @Override protected final T compute() {
1351              try {
1352                  return realCompute();
1353 <            } catch (Throwable t) {
1354 <                threadUnexpectedException(t);
1353 >            } catch (Throwable fail) {
1354 >                threadUnexpectedException(fail);
1355                  return null;
1356              }
1357          }
# Line 1060 | Line 1366 | public class JSR166TestCase extends Test
1366      }
1367  
1368      /**
1369 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1370 <     * of throwing checked exceptions.
1369 >     * A CyclicBarrier that uses timed await and fails with
1370 >     * AssertionFailedErrors instead of throwing checked exceptions.
1371       */
1372      public class CheckedBarrier extends CyclicBarrier {
1373          public CheckedBarrier(int parties) { super(parties); }
1374  
1375          public int await() {
1376              try {
1377 <                return super.await();
1378 <            } catch (Exception e) {
1377 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1378 >            } catch (TimeoutException timedOut) {
1379 >                throw new AssertionFailedError("timed out");
1380 >            } catch (Exception fail) {
1381                  AssertionFailedError afe =
1382 <                    new AssertionFailedError("Unexpected exception: " + e);
1383 <                afe.initCause(e);
1382 >                    new AssertionFailedError("Unexpected exception: " + fail);
1383 >                afe.initCause(fail);
1384                  throw afe;
1385              }
1386          }
1387      }
1388  
1389 <    public void checkEmpty(BlockingQueue q) {
1389 >    void checkEmpty(BlockingQueue q) {
1390          try {
1391              assertTrue(q.isEmpty());
1392              assertEquals(0, q.size());
# Line 1100 | Line 1408 | public class JSR166TestCase extends Test
1408                  q.remove();
1409                  shouldThrow();
1410              } catch (NoSuchElementException success) {}
1411 <        } catch (InterruptedException ie) {
1104 <            threadUnexpectedException(ie);
1105 <        }
1411 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1412      }
1413  
1414 <    @SuppressWarnings("unchecked")
1415 <    public <T> T serialClone(T o) {
1414 >    void assertSerialEquals(Object x, Object y) {
1415 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1416 >    }
1417 >
1418 >    void assertNotSerialEquals(Object x, Object y) {
1419 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1420 >    }
1421 >
1422 >    byte[] serialBytes(Object o) {
1423          try {
1424              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1425              ObjectOutputStream oos = new ObjectOutputStream(bos);
1426              oos.writeObject(o);
1427              oos.flush();
1428              oos.close();
1429 <            ByteArrayInputStream bin =
1430 <                new ByteArrayInputStream(bos.toByteArray());
1431 <            ObjectInputStream ois = new ObjectInputStream(bin);
1432 <            return (T) ois.readObject();
1433 <        } catch (Throwable t) {
1434 <            threadUnexpectedException(t);
1429 >            return bos.toByteArray();
1430 >        } catch (Throwable fail) {
1431 >            threadUnexpectedException(fail);
1432 >            return new byte[0];
1433 >        }
1434 >    }
1435 >
1436 >    @SuppressWarnings("unchecked")
1437 >    <T> T serialClone(T o) {
1438 >        try {
1439 >            ObjectInputStream ois = new ObjectInputStream
1440 >                (new ByteArrayInputStream(serialBytes(o)));
1441 >            T clone = (T) ois.readObject();
1442 >            assertSame(o.getClass(), clone.getClass());
1443 >            return clone;
1444 >        } catch (Throwable fail) {
1445 >            threadUnexpectedException(fail);
1446              return null;
1447          }
1448      }
1449 +
1450 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1451 +                             Runnable... throwingActions) {
1452 +        for (Runnable throwingAction : throwingActions) {
1453 +            boolean threw = false;
1454 +            try { throwingAction.run(); }
1455 +            catch (Throwable t) {
1456 +                threw = true;
1457 +                if (!expectedExceptionClass.isInstance(t)) {
1458 +                    AssertionFailedError afe =
1459 +                        new AssertionFailedError
1460 +                        ("Expected " + expectedExceptionClass.getName() +
1461 +                         ", got " + t.getClass().getName());
1462 +                    afe.initCause(t);
1463 +                    threadUnexpectedException(afe);
1464 +                }
1465 +            }
1466 +            if (!threw)
1467 +                shouldThrow(expectedExceptionClass.getName());
1468 +        }
1469 +    }
1470 +
1471 +    public void assertIteratorExhausted(Iterator<?> it) {
1472 +        try {
1473 +            it.next();
1474 +            shouldThrow();
1475 +        } catch (NoSuchElementException success) {}
1476 +        assertFalse(it.hasNext());
1477 +    }
1478   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines