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.85 by jsr166, Sun May 29 14:18:52 2011 UTC vs.
Revision 1.135 by jsr166, Fri Jul 3 05:48:30 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.Date;
18 < import java.util.NoSuchElementException;
19 < import java.util.PropertyPermission;
20 < import java.util.concurrent.*;
19 < import java.util.concurrent.atomic.AtomicBoolean;
20 < import java.util.concurrent.atomic.AtomicReference;
21 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
16 > import java.lang.management.ManagementFactory;
17 > import java.lang.management.ThreadInfo;
18 > import java.lang.reflect.Constructor;
19 > import java.lang.reflect.Method;
20 > import java.lang.reflect.Modifier;
21   import java.security.CodeSource;
22   import java.security.Permission;
23   import java.security.PermissionCollection;
# Line 27 | Line 25 | import java.security.Permissions;
25   import java.security.Policy;
26   import java.security.ProtectionDomain;
27   import java.security.SecurityPermission;
28 + import java.util.ArrayList;
29 + import java.util.Arrays;
30 + import java.util.Date;
31 + import java.util.Enumeration;
32 + import java.util.Iterator;
33 + import java.util.List;
34 + import java.util.NoSuchElementException;
35 + import java.util.PropertyPermission;
36 + import java.util.concurrent.BlockingQueue;
37 + import java.util.concurrent.Callable;
38 + import java.util.concurrent.CountDownLatch;
39 + import java.util.concurrent.CyclicBarrier;
40 + import java.util.concurrent.ExecutorService;
41 + import java.util.concurrent.Future;
42 + import java.util.concurrent.RecursiveAction;
43 + import java.util.concurrent.RecursiveTask;
44 + import java.util.concurrent.RejectedExecutionHandler;
45 + import java.util.concurrent.Semaphore;
46 + import java.util.concurrent.ThreadFactory;
47 + import java.util.concurrent.ThreadPoolExecutor;
48 + import java.util.concurrent.TimeoutException;
49 + import java.util.concurrent.atomic.AtomicReference;
50 + import java.util.regex.Pattern;
51 +
52 + import junit.framework.AssertionFailedError;
53 + import junit.framework.Test;
54 + import junit.framework.TestCase;
55 + import junit.framework.TestResult;
56 + import junit.framework.TestSuite;
57  
58   /**
59   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 69 | Line 96 | import java.security.SecurityPermission;
96   *
97   * </ol>
98   *
99 < * <p> <b>Other notes</b>
99 > * <p><b>Other notes</b>
100   * <ul>
101   *
102   * <li> Usually, there is one testcase method per JSR166 method
# Line 109 | Line 136 | public class JSR166TestCase extends Test
136          Boolean.getBoolean("jsr166.expensiveTests");
137  
138      /**
139 +     * If true, also run tests that are not part of the official tck
140 +     * because they test unspecified implementation details.
141 +     */
142 +    protected static final boolean testImplementationDetails =
143 +        Boolean.getBoolean("jsr166.testImplementationDetails");
144 +
145 +    /**
146       * If true, report on stdout all "slow" tests, that is, ones that
147       * take more than profileThreshold milliseconds to execute.
148       */
# Line 122 | Line 156 | public class JSR166TestCase extends Test
156      private static final long profileThreshold =
157          Long.getLong("jsr166.profileThreshold", 100);
158  
159 +    /**
160 +     * The number of repetitions per test (for tickling rare bugs).
161 +     */
162 +    private static final int runsPerTest =
163 +        Integer.getInteger("jsr166.runsPerTest", 1);
164 +
165 +    /**
166 +     * The number of repetitions of the test suite (for finding leaks?).
167 +     */
168 +    private static final int suiteRuns =
169 +        Integer.getInteger("jsr166.suiteRuns", 1);
170 +
171 +    public JSR166TestCase() { super(); }
172 +    public JSR166TestCase(String name) { super(name); }
173 +
174 +    /**
175 +     * A filter for tests to run, matching strings of the form
176 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
177 +     * Usefully combined with jsr166.runsPerTest.
178 +     */
179 +    private static final Pattern methodFilter = methodFilter();
180 +
181 +    private static Pattern methodFilter() {
182 +        String regex = System.getProperty("jsr166.methodFilter");
183 +        return (regex == null) ? null : Pattern.compile(regex);
184 +    }
185 +
186      protected void runTest() throws Throwable {
187 <        if (profileTests)
188 <            runTestProfiled();
189 <        else
190 <            super.runTest();
187 >        if (methodFilter == null
188 >            || methodFilter.matcher(toString()).find()) {
189 >            for (int i = 0; i < runsPerTest; i++) {
190 >                if (profileTests)
191 >                    runTestProfiled();
192 >                else
193 >                    super.runTest();
194 >            }
195 >        }
196      }
197  
198      protected void runTestProfiled() throws Throwable {
199 +        // Warmup run, notably to trigger all needed classloading.
200 +        super.runTest();
201          long t0 = System.nanoTime();
202          try {
203              super.runTest();
204          } finally {
205 <            long elapsedMillis =
138 <                (System.nanoTime() - t0) / (1000L * 1000L);
205 >            long elapsedMillis = millisElapsedSince(t0);
206              if (elapsedMillis >= profileThreshold)
207                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
208          }
209      }
210  
211      /**
212 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
212 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
213       */
214      public static void main(String[] args) {
215 +        main(suite(), args);
216 +    }
217 +
218 +    /**
219 +     * Runs all unit tests in the given test suite.
220 +     * Actual behavior influenced by jsr166.* system properties.
221 +     */
222 +    static void main(Test suite, String[] args) {
223          if (useSecurityManager) {
224              System.err.println("Setting a permissive security manager");
225              Policy.setPolicy(permissivePolicy());
226              System.setSecurityManager(new SecurityManager());
227          }
228 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
229 <
230 <        Test s = suite();
231 <        for (int i = 0; i < iters; ++i) {
157 <            junit.textui.TestRunner.run(s);
228 >        for (int i = 0; i < suiteRuns; i++) {
229 >            TestResult result = junit.textui.TestRunner.run(suite);
230 >            if (!result.wasSuccessful())
231 >                System.exit(1);
232              System.gc();
233              System.runFinalization();
234          }
161        System.exit(0);
235      }
236  
237      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 174 | Line 247 | public class JSR166TestCase extends Test
247          return suite;
248      }
249  
250 +    public static void addNamedTestClasses(TestSuite suite,
251 +                                           String... testClassNames) {
252 +        for (String testClassName : testClassNames) {
253 +            try {
254 +                Class<?> testClass = Class.forName(testClassName);
255 +                Method m = testClass.getDeclaredMethod("suite",
256 +                                                       new Class<?>[0]);
257 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
258 +            } catch (Exception e) {
259 +                throw new Error("Missing test class", e);
260 +            }
261 +        }
262 +    }
263 +
264 +    public static final double JAVA_CLASS_VERSION;
265 +    public static final String JAVA_SPECIFICATION_VERSION;
266 +    static {
267 +        try {
268 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
269 +                new java.security.PrivilegedAction<Double>() {
270 +                public Double run() {
271 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
272 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
273 +                new java.security.PrivilegedAction<String>() {
274 +                public String run() {
275 +                    return System.getProperty("java.specification.version");}});
276 +        } catch (Throwable t) {
277 +            throw new Error(t);
278 +        }
279 +    }
280 +
281 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
282 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
283 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
284 +    public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
285 +
286      /**
287       * Collects all JSR166 unit tests as one suite.
288       */
289      public static Test suite() {
290 <        return newTestSuite(
290 >        // Java7+ test classes
291 >        TestSuite suite = newTestSuite(
292              ForkJoinPoolTest.suite(),
293              ForkJoinTaskTest.suite(),
294              RecursiveActionTest.suite(),
# Line 243 | Line 353 | public class JSR166TestCase extends Test
353              TreeSetTest.suite(),
354              TreeSubMapTest.suite(),
355              TreeSubSetTest.suite());
356 +
357 +        // Java8+ test classes
358 +        if (atLeastJava8()) {
359 +            String[] java8TestClassNames = {
360 +                "Atomic8Test",
361 +                "CompletableFutureTest",
362 +                "ConcurrentHashMap8Test",
363 +                "CountedCompleterTest",
364 +                "DoubleAccumulatorTest",
365 +                "DoubleAdderTest",
366 +                "ForkJoinPool8Test",
367 +                "ForkJoinTask8Test",
368 +                "LongAccumulatorTest",
369 +                "LongAdderTest",
370 +                "SplittableRandomTest",
371 +                "StampedLockTest",
372 +                "ThreadLocalRandom8Test",
373 +            };
374 +            addNamedTestClasses(suite, java8TestClassNames);
375 +        }
376 +
377 +        // Java9+ test classes
378 +        if (atLeastJava9()) {
379 +            String[] java9TestClassNames = {
380 +                "ThreadPoolExecutor9Test",
381 +            };
382 +            addNamedTestClasses(suite, java9TestClassNames);
383 +        }
384 +
385 +        return suite;
386 +    }
387 +
388 +    /** Returns list of junit-style test method names in given class. */
389 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
390 +        Method[] methods = testClass.getDeclaredMethods();
391 +        ArrayList<String> names = new ArrayList<String>(methods.length);
392 +        for (Method method : methods) {
393 +            if (method.getName().startsWith("test")
394 +                && Modifier.isPublic(method.getModifiers())
395 +                // method.getParameterCount() requires jdk8+
396 +                && method.getParameterTypes().length == 0) {
397 +                names.add(method.getName());
398 +            }
399 +        }
400 +        return names;
401 +    }
402 +
403 +    /**
404 +     * Returns junit-style testSuite for the given test class, but
405 +     * parameterized by passing extra data to each test.
406 +     */
407 +    public static <ExtraData> Test parameterizedTestSuite
408 +        (Class<? extends JSR166TestCase> testClass,
409 +         Class<ExtraData> dataClass,
410 +         ExtraData data) {
411 +        try {
412 +            TestSuite suite = new TestSuite();
413 +            Constructor c =
414 +                testClass.getDeclaredConstructor(dataClass, String.class);
415 +            for (String methodName : testMethodNames(testClass))
416 +                suite.addTest((Test) c.newInstance(data, methodName));
417 +            return suite;
418 +        } catch (Exception e) {
419 +            throw new Error(e);
420 +        }
421 +    }
422 +
423 +    /**
424 +     * Returns junit-style testSuite for the jdk8 extension of the
425 +     * given test class, but parameterized by passing extra data to
426 +     * each test.  Uses reflection to allow compilation in jdk7.
427 +     */
428 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
429 +        (Class<? extends JSR166TestCase> testClass,
430 +         Class<ExtraData> dataClass,
431 +         ExtraData data) {
432 +        if (atLeastJava8()) {
433 +            String name = testClass.getName();
434 +            String name8 = name.replaceAll("Test$", "8Test");
435 +            if (name.equals(name8)) throw new Error(name);
436 +            try {
437 +                return (Test)
438 +                    Class.forName(name8)
439 +                    .getMethod("testSuite", new Class[] { dataClass })
440 +                    .invoke(null, data);
441 +            } catch (Exception e) {
442 +                throw new Error(e);
443 +            }
444 +        } else {
445 +            return new TestSuite();
446 +        }
447 +
448      }
449  
450 +    // Delays for timing-dependent tests, in milliseconds.
451  
452      public static long SHORT_DELAY_MS;
453      public static long SMALL_DELAY_MS;
454      public static long MEDIUM_DELAY_MS;
455      public static long LONG_DELAY_MS;
456  
254
457      /**
458       * Returns the shortest timed delay. This could
459       * be reimplemented to use for example a Property.
# Line 279 | Line 481 | public class JSR166TestCase extends Test
481      }
482  
483      /**
484 <     * Returns a new Date instance representing a time delayMillis
485 <     * milliseconds in the future.
484 >     * Returns a new Date instance representing a time at least
485 >     * delayMillis milliseconds in the future.
486       */
487      Date delayedDate(long delayMillis) {
488 <        return new Date(System.currentTimeMillis() + delayMillis);
488 >        // Add 1 because currentTimeMillis is known to round into the past.
489 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
490      }
491  
492      /**
# Line 334 | Line 537 | public class JSR166TestCase extends Test
537  
538          if (Thread.interrupted())
539              throw new AssertionFailedError("interrupt status set in main thread");
540 +
541 +        checkForkJoinPoolThreadLeaks();
542 +    }
543 +
544 +    /**
545 +     * Finds missing try { ... } finally { joinPool(e); }
546 +     */
547 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
548 +        Thread[] survivors = new Thread[5];
549 +        int count = Thread.enumerate(survivors);
550 +        for (int i = 0; i < count; i++) {
551 +            Thread thread = survivors[i];
552 +            String name = thread.getName();
553 +            if (name.startsWith("ForkJoinPool-")) {
554 +                // give thread some time to terminate
555 +                thread.join(LONG_DELAY_MS);
556 +                if (!thread.isAlive()) continue;
557 +                throw new AssertionFailedError
558 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
559 +                                   toString(), name));
560 +            }
561 +        }
562      }
563  
564      /**
# Line 414 | Line 639 | public class JSR166TestCase extends Test
639      public void threadAssertEquals(Object x, Object y) {
640          try {
641              assertEquals(x, y);
642 <        } catch (AssertionFailedError t) {
643 <            threadRecordFailure(t);
644 <            throw t;
645 <        } catch (Throwable t) {
646 <            threadUnexpectedException(t);
642 >        } catch (AssertionFailedError fail) {
643 >            threadRecordFailure(fail);
644 >            throw fail;
645 >        } catch (Throwable fail) {
646 >            threadUnexpectedException(fail);
647          }
648      }
649  
# Line 430 | Line 655 | public class JSR166TestCase extends Test
655      public void threadAssertSame(Object x, Object y) {
656          try {
657              assertSame(x, y);
658 <        } catch (AssertionFailedError t) {
659 <            threadRecordFailure(t);
660 <            throw t;
658 >        } catch (AssertionFailedError fail) {
659 >            threadRecordFailure(fail);
660 >            throw fail;
661          }
662      }
663  
# Line 497 | Line 722 | public class JSR166TestCase extends Test
722      void joinPool(ExecutorService exec) {
723          try {
724              exec.shutdown();
725 <            assertTrue("ExecutorService did not terminate in a timely manner",
726 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
725 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
726 >                fail("ExecutorService " + exec +
727 >                     " did not terminate in a timely manner");
728          } catch (SecurityException ok) {
729              // Allowed in case test doesn't have privs
730 <        } catch (InterruptedException ie) {
730 >        } catch (InterruptedException fail) {
731              fail("Unexpected InterruptedException");
732          }
733      }
734  
735      /**
736 +     * A debugging tool to print all stack traces, as jstack does.
737 +     */
738 +    static void printAllStackTraces() {
739 +        for (ThreadInfo info :
740 +                 ManagementFactory.getThreadMXBean()
741 +                 .dumpAllThreads(true, true))
742 +            System.err.print(info);
743 +    }
744 +
745 +    /**
746       * Checks that thread does not terminate within the default
747       * millisecond delay of {@code timeoutMillis()}.
748       */
# Line 522 | Line 758 | public class JSR166TestCase extends Test
758              // No need to optimize the failing case via Thread.join.
759              delay(millis);
760              assertTrue(thread.isAlive());
761 <        } catch (InterruptedException ie) {
761 >        } catch (InterruptedException fail) {
762 >            fail("Unexpected InterruptedException");
763 >        }
764 >    }
765 >
766 >    /**
767 >     * Checks that the threads do not terminate within the default
768 >     * millisecond delay of {@code timeoutMillis()}.
769 >     */
770 >    void assertThreadsStayAlive(Thread... threads) {
771 >        assertThreadsStayAlive(timeoutMillis(), threads);
772 >    }
773 >
774 >    /**
775 >     * Checks that the threads do not terminate within the given millisecond delay.
776 >     */
777 >    void assertThreadsStayAlive(long millis, Thread... threads) {
778 >        try {
779 >            // No need to optimize the failing case via Thread.join.
780 >            delay(millis);
781 >            for (Thread thread : threads)
782 >                assertTrue(thread.isAlive());
783 >        } catch (InterruptedException fail) {
784              fail("Unexpected InterruptedException");
785          }
786      }
# Line 544 | Line 802 | public class JSR166TestCase extends Test
802              future.get(timeoutMillis, MILLISECONDS);
803              shouldThrow();
804          } catch (TimeoutException success) {
805 <        } catch (Exception e) {
806 <            threadUnexpectedException(e);
805 >        } catch (Exception fail) {
806 >            threadUnexpectedException(fail);
807          } finally { future.cancel(true); }
808          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
809      }
# Line 589 | Line 847 | public class JSR166TestCase extends Test
847      public static final Integer m6  = new Integer(-6);
848      public static final Integer m10 = new Integer(-10);
849  
592
850      /**
851       * Runs Runnable r with a security policy that permits precisely
852       * the specified permissions.  If there is no current security
# Line 601 | Line 858 | public class JSR166TestCase extends Test
858          SecurityManager sm = System.getSecurityManager();
859          if (sm == null) {
860              r.run();
861 +        }
862 +        runWithSecurityManagerWithPermissions(r, permissions);
863 +    }
864 +
865 +    /**
866 +     * Runs Runnable r with a security policy that permits precisely
867 +     * the specified permissions.  If there is no current security
868 +     * manager, a temporary one is set for the duration of the
869 +     * Runnable.  We require that any security manager permit
870 +     * getPolicy/setPolicy.
871 +     */
872 +    public void runWithSecurityManagerWithPermissions(Runnable r,
873 +                                                      Permission... permissions) {
874 +        SecurityManager sm = System.getSecurityManager();
875 +        if (sm == null) {
876              Policy savedPolicy = Policy.getPolicy();
877              try {
878                  Policy.setPolicy(permissivePolicy());
879                  System.setSecurityManager(new SecurityManager());
880 <                runWithPermissions(r, permissions);
880 >                runWithSecurityManagerWithPermissions(r, permissions);
881              } finally {
882                  System.setSecurityManager(null);
883                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 925 | public class JSR166TestCase extends Test
925              return perms.implies(p);
926          }
927          public void refresh() {}
928 +        public String toString() {
929 +            List<Permission> ps = new ArrayList<Permission>();
930 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
931 +                ps.add(e.nextElement());
932 +            return "AdjustablePolicy with permissions " + ps;
933 +        }
934      }
935  
936      /**
# Line 681 | Line 959 | public class JSR166TestCase extends Test
959      void sleep(long millis) {
960          try {
961              delay(millis);
962 <        } catch (InterruptedException ie) {
962 >        } catch (InterruptedException fail) {
963              AssertionFailedError afe =
964                  new AssertionFailedError("Unexpected InterruptedException");
965 <            afe.initCause(ie);
965 >            afe.initCause(fail);
966              throw afe;
967          }
968      }
969  
970      /**
971 <     * Waits up to the specified number of milliseconds for the given
971 >     * Spin-waits up to the specified number of milliseconds for the given
972       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
973       */
974      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
975 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
975 >        long startTime = System.nanoTime();
976          for (;;) {
977              Thread.State s = thread.getState();
978              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 981 | public class JSR166TestCase extends Test
981                  return;
982              else if (s == Thread.State.TERMINATED)
983                  fail("Unexpected thread termination");
984 <            else if (System.nanoTime() - t0 > timeoutNanos) {
984 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
985                  threadAssertTrue(thread.isAlive());
986                  return;
987              }
# Line 723 | Line 1000 | public class JSR166TestCase extends Test
1000      /**
1001       * Returns the number of milliseconds since time given by
1002       * startNanoTime, which must have been previously returned from a
1003 <     * call to {@link System.nanoTime()}.
1003 >     * call to {@link System#nanoTime()}.
1004       */
1005 <    long millisElapsedSince(long startNanoTime) {
1005 >    static long millisElapsedSince(long startNanoTime) {
1006          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1007      }
1008  
1009 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1010 + //         long startTime = System.nanoTime();
1011 + //         try {
1012 + //             r.run();
1013 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1014 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1015 + //             throw new AssertionFailedError("did not return promptly");
1016 + //     }
1017 +
1018 + //     void assertTerminatesPromptly(Runnable r) {
1019 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1020 + //     }
1021 +
1022 +    /**
1023 +     * Checks that timed f.get() returns the expected value, and does not
1024 +     * wait for the timeout to elapse before returning.
1025 +     */
1026 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1027 +        long startTime = System.nanoTime();
1028 +        try {
1029 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1030 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1031 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1032 +            throw new AssertionFailedError("timed get did not return promptly");
1033 +    }
1034 +
1035 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1036 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1037 +    }
1038 +
1039      /**
1040       * Returns a new started daemon Thread running the given runnable.
1041       */
# Line 747 | Line 1054 | public class JSR166TestCase extends Test
1054      void awaitTermination(Thread t, long timeoutMillis) {
1055          try {
1056              t.join(timeoutMillis);
1057 <        } catch (InterruptedException ie) {
1058 <            threadUnexpectedException(ie);
1057 >        } catch (InterruptedException fail) {
1058 >            threadUnexpectedException(fail);
1059          } finally {
1060              if (t.getState() != Thread.State.TERMINATED) {
1061                  t.interrupt();
# Line 774 | Line 1081 | public class JSR166TestCase extends Test
1081          public final void run() {
1082              try {
1083                  realRun();
1084 <            } catch (Throwable t) {
1085 <                threadUnexpectedException(t);
1084 >            } catch (Throwable fail) {
1085 >                threadUnexpectedException(fail);
1086              }
1087          }
1088      }
# Line 829 | Line 1136 | public class JSR166TestCase extends Test
1136                  threadShouldThrow("InterruptedException");
1137              } catch (InterruptedException success) {
1138                  threadAssertFalse(Thread.interrupted());
1139 <            } catch (Throwable t) {
1140 <                threadUnexpectedException(t);
1139 >            } catch (Throwable fail) {
1140 >                threadUnexpectedException(fail);
1141              }
1142          }
1143      }
# Line 841 | Line 1148 | public class JSR166TestCase extends Test
1148          public final T call() {
1149              try {
1150                  return realCall();
1151 <            } catch (Throwable t) {
1152 <                threadUnexpectedException(t);
1151 >            } catch (Throwable fail) {
1152 >                threadUnexpectedException(fail);
1153                  return null;
1154              }
1155          }
# Line 859 | Line 1166 | public class JSR166TestCase extends Test
1166                  return result;
1167              } catch (InterruptedException success) {
1168                  threadAssertFalse(Thread.interrupted());
1169 <            } catch (Throwable t) {
1170 <                threadUnexpectedException(t);
1169 >            } catch (Throwable fail) {
1170 >                threadUnexpectedException(fail);
1171              }
1172              return null;
1173          }
# Line 900 | Line 1207 | public class JSR166TestCase extends Test
1207      public void await(CountDownLatch latch) {
1208          try {
1209              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1210 <        } catch (Throwable t) {
1211 <            threadUnexpectedException(t);
1210 >        } catch (Throwable fail) {
1211 >            threadUnexpectedException(fail);
1212 >        }
1213 >    }
1214 >
1215 >    public void await(Semaphore semaphore) {
1216 >        try {
1217 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1218 >        } catch (Throwable fail) {
1219 >            threadUnexpectedException(fail);
1220          }
1221      }
1222  
# Line 1092 | Line 1407 | public class JSR166TestCase extends Test
1407      public abstract class CheckedRecursiveAction extends RecursiveAction {
1408          protected abstract void realCompute() throws Throwable;
1409  
1410 <        public final void compute() {
1410 >        @Override protected final void compute() {
1411              try {
1412                  realCompute();
1413 <            } catch (Throwable t) {
1414 <                threadUnexpectedException(t);
1413 >            } catch (Throwable fail) {
1414 >                threadUnexpectedException(fail);
1415              }
1416          }
1417      }
# Line 1107 | Line 1422 | public class JSR166TestCase extends Test
1422      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1423          protected abstract T realCompute() throws Throwable;
1424  
1425 <        public final T compute() {
1425 >        @Override protected final T compute() {
1426              try {
1427                  return realCompute();
1428 <            } catch (Throwable t) {
1429 <                threadUnexpectedException(t);
1428 >            } catch (Throwable fail) {
1429 >                threadUnexpectedException(fail);
1430                  return null;
1431              }
1432          }
# Line 1126 | Line 1441 | public class JSR166TestCase extends Test
1441      }
1442  
1443      /**
1444 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1445 <     * of throwing checked exceptions.
1444 >     * A CyclicBarrier that uses timed await and fails with
1445 >     * AssertionFailedErrors instead of throwing checked exceptions.
1446       */
1447      public class CheckedBarrier extends CyclicBarrier {
1448          public CheckedBarrier(int parties) { super(parties); }
1449  
1450          public int await() {
1451              try {
1452 <                return super.await();
1453 <            } catch (Exception e) {
1452 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1453 >            } catch (TimeoutException timedOut) {
1454 >                throw new AssertionFailedError("timed out");
1455 >            } catch (Exception fail) {
1456                  AssertionFailedError afe =
1457 <                    new AssertionFailedError("Unexpected exception: " + e);
1458 <                afe.initCause(e);
1457 >                    new AssertionFailedError("Unexpected exception: " + fail);
1458 >                afe.initCause(fail);
1459                  throw afe;
1460              }
1461          }
# Line 1166 | Line 1483 | public class JSR166TestCase extends Test
1483                  q.remove();
1484                  shouldThrow();
1485              } catch (NoSuchElementException success) {}
1486 <        } catch (InterruptedException ie) {
1170 <            threadUnexpectedException(ie);
1171 <        }
1486 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1487      }
1488  
1489 <    @SuppressWarnings("unchecked")
1490 <    <T> T serialClone(T o) {
1489 >    void assertSerialEquals(Object x, Object y) {
1490 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1491 >    }
1492 >
1493 >    void assertNotSerialEquals(Object x, Object y) {
1494 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1495 >    }
1496 >
1497 >    byte[] serialBytes(Object o) {
1498          try {
1499              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1500              ObjectOutputStream oos = new ObjectOutputStream(bos);
1501              oos.writeObject(o);
1502              oos.flush();
1503              oos.close();
1504 <            ByteArrayInputStream bin =
1505 <                new ByteArrayInputStream(bos.toByteArray());
1506 <            ObjectInputStream ois = new ObjectInputStream(bin);
1507 <            return (T) ois.readObject();
1508 <        } catch (Throwable t) {
1509 <            threadUnexpectedException(t);
1504 >            return bos.toByteArray();
1505 >        } catch (Throwable fail) {
1506 >            threadUnexpectedException(fail);
1507 >            return new byte[0];
1508 >        }
1509 >    }
1510 >
1511 >    @SuppressWarnings("unchecked")
1512 >    <T> T serialClone(T o) {
1513 >        try {
1514 >            ObjectInputStream ois = new ObjectInputStream
1515 >                (new ByteArrayInputStream(serialBytes(o)));
1516 >            T clone = (T) ois.readObject();
1517 >            assertSame(o.getClass(), clone.getClass());
1518 >            return clone;
1519 >        } catch (Throwable fail) {
1520 >            threadUnexpectedException(fail);
1521              return null;
1522          }
1523      }
1524 +
1525 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1526 +                             Runnable... throwingActions) {
1527 +        for (Runnable throwingAction : throwingActions) {
1528 +            boolean threw = false;
1529 +            try { throwingAction.run(); }
1530 +            catch (Throwable t) {
1531 +                threw = true;
1532 +                if (!expectedExceptionClass.isInstance(t)) {
1533 +                    AssertionFailedError afe =
1534 +                        new AssertionFailedError
1535 +                        ("Expected " + expectedExceptionClass.getName() +
1536 +                         ", got " + t.getClass().getName());
1537 +                    afe.initCause(t);
1538 +                    threadUnexpectedException(afe);
1539 +                }
1540 +            }
1541 +            if (!threw)
1542 +                shouldThrow(expectedExceptionClass.getName());
1543 +        }
1544 +    }
1545 +
1546 +    public void assertIteratorExhausted(Iterator<?> it) {
1547 +        try {
1548 +            it.next();
1549 +            shouldThrow();
1550 +        } catch (NoSuchElementException success) {}
1551 +        assertFalse(it.hasNext());
1552 +    }
1553   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines