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.69 by dl, Fri Nov 19 00:20:12 2010 UTC vs.
Revision 1.131 by jsr166, Sat Apr 25 04:55:30 2015 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.util.PropertyPermission;
11 import java.util.concurrent.*;
12 import java.util.concurrent.atomic.AtomicReference;
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.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 19 | 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.TestResult;
54 + import junit.framework.TestSuite;
55  
56   /**
57   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 61 | Line 94 | import java.security.SecurityPermission;
94   *
95   * </ol>
96   *
97 < * <p> <b>Other notes</b>
97 > * <p><b>Other notes</b>
98   * <ul>
99   *
100   * <li> Usually, there is one testcase method per JSR166 method
# Line 101 | Line 134 | public class JSR166TestCase extends Test
134          Boolean.getBoolean("jsr166.expensiveTests");
135  
136      /**
137 +     * If true, also run tests that are not part of the official tck
138 +     * because they test unspecified implementation details.
139 +     */
140 +    protected static final boolean testImplementationDetails =
141 +        Boolean.getBoolean("jsr166.testImplementationDetails");
142 +
143 +    /**
144       * If true, report on stdout all "slow" tests, that is, ones that
145       * take more than profileThreshold milliseconds to execute.
146       */
# Line 114 | Line 154 | public class JSR166TestCase extends Test
154      private static final long profileThreshold =
155          Long.getLong("jsr166.profileThreshold", 100);
156  
157 +    /**
158 +     * The number of repetitions per test (for tickling rare bugs).
159 +     */
160 +    private static final int runsPerTest =
161 +        Integer.getInteger("jsr166.runsPerTest", 1);
162 +
163 +    /**
164 +     * The number of repetitions of the test suite (for finding leaks?).
165 +     */
166 +    private static final int suiteRuns =
167 +        Integer.getInteger("jsr166.suiteRuns", 1);
168 +
169 +    /**
170 +     * A filter for tests to run, matching strings of the form
171 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
172 +     * Usefully combined with jsr166.runsPerTest.
173 +     */
174 +    private static final Pattern methodFilter = methodFilter();
175 +
176 +    private static Pattern methodFilter() {
177 +        String regex = System.getProperty("jsr166.methodFilter");
178 +        return (regex == null) ? null : Pattern.compile(regex);
179 +    }
180 +
181      protected void runTest() throws Throwable {
182 <        if (profileTests)
183 <            runTestProfiled();
184 <        else
185 <            super.runTest();
182 >        if (methodFilter == null
183 >            || methodFilter.matcher(toString()).find()) {
184 >            for (int i = 0; i < runsPerTest; i++) {
185 >                if (profileTests)
186 >                    runTestProfiled();
187 >                else
188 >                    super.runTest();
189 >            }
190 >        }
191      }
192  
193      protected void runTestProfiled() throws Throwable {
194 +        // Warmup run, notably to trigger all needed classloading.
195 +        super.runTest();
196          long t0 = System.nanoTime();
197          try {
198              super.runTest();
199          } finally {
200 <            long elapsedMillis =
130 <                (System.nanoTime() - t0) / (1000L * 1000L);
200 >            long elapsedMillis = millisElapsedSince(t0);
201              if (elapsedMillis >= profileThreshold)
202                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
203          }
204      }
205  
206      /**
207 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
207 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
208       */
209      public static void main(String[] args) {
210 +        main(suite(), args);
211 +    }
212 +
213 +    /**
214 +     * Runs all unit tests in the given test suite.
215 +     * Actual behavior influenced by system properties jsr166.*
216 +     */
217 +    static void main(Test suite, String[] args) {
218          if (useSecurityManager) {
219              System.err.println("Setting a permissive security manager");
220              Policy.setPolicy(permissivePolicy());
221              System.setSecurityManager(new SecurityManager());
222          }
223 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
224 <
225 <        Test s = suite();
226 <        for (int i = 0; i < iters; ++i) {
149 <            junit.textui.TestRunner.run(s);
223 >        for (int i = 0; i < suiteRuns; i++) {
224 >            TestResult result = junit.textui.TestRunner.run(suite);
225 >            if (!result.wasSuccessful())
226 >                System.exit(1);
227              System.gc();
228              System.runFinalization();
229          }
153        System.exit(0);
230      }
231  
232      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 166 | Line 242 | public class JSR166TestCase extends Test
242          return suite;
243      }
244  
245 +    public static void addNamedTestClasses(TestSuite suite,
246 +                                           String... testClassNames) {
247 +        for (String testClassName : testClassNames) {
248 +            try {
249 +                Class<?> testClass = Class.forName(testClassName);
250 +                Method m = testClass.getDeclaredMethod("suite",
251 +                                                       new Class<?>[0]);
252 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
253 +            } catch (Exception e) {
254 +                throw new Error("Missing test class", e);
255 +            }
256 +        }
257 +    }
258 +
259 +    public static final double JAVA_CLASS_VERSION;
260 +    public static final String JAVA_SPECIFICATION_VERSION;
261 +    static {
262 +        try {
263 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
264 +                new java.security.PrivilegedAction<Double>() {
265 +                public Double run() {
266 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
267 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
268 +                new java.security.PrivilegedAction<String>() {
269 +                public String run() {
270 +                    return System.getProperty("java.specification.version");}});
271 +        } catch (Throwable t) {
272 +            throw new Error(t);
273 +        }
274 +    }
275 +
276 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
277 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
278 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
279 +    public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
280 +
281      /**
282       * Collects all JSR166 unit tests as one suite.
283       */
284      public static Test suite() {
285 <        return newTestSuite(
285 >        // Java7+ test classes
286 >        TestSuite suite = newTestSuite(
287              ForkJoinPoolTest.suite(),
288              ForkJoinTaskTest.suite(),
289              RecursiveActionTest.suite(),
# Line 235 | Line 348 | public class JSR166TestCase extends Test
348              TreeSetTest.suite(),
349              TreeSubMapTest.suite(),
350              TreeSubSetTest.suite());
351 +
352 +        // Java8+ test classes
353 +        if (atLeastJava8()) {
354 +            String[] java8TestClassNames = {
355 +                "Atomic8Test",
356 +                "CompletableFutureTest",
357 +                "ConcurrentHashMap8Test",
358 +                "CountedCompleterTest",
359 +                "DoubleAccumulatorTest",
360 +                "DoubleAdderTest",
361 +                "ForkJoinPool8Test",
362 +                "ForkJoinTask8Test",
363 +                "LongAccumulatorTest",
364 +                "LongAdderTest",
365 +                "SplittableRandomTest",
366 +                "StampedLockTest",
367 +                "ThreadLocalRandom8Test",
368 +            };
369 +            addNamedTestClasses(suite, java8TestClassNames);
370 +        }
371 +
372 +        // Java9+ test classes
373 +        if (atLeastJava9()) {
374 +            String[] java9TestClassNames = {
375 +                "ThreadPoolExecutor9Test",
376 +            };
377 +            addNamedTestClasses(suite, java9TestClassNames);
378 +        }
379 +
380 +        return suite;
381      }
382  
383 +    // Delays for timing-dependent tests, in milliseconds.
384  
385      public static long SHORT_DELAY_MS;
386      public static long SMALL_DELAY_MS;
387      public static long MEDIUM_DELAY_MS;
388      public static long LONG_DELAY_MS;
389  
246
390      /**
391       * Returns the shortest timed delay. This could
392       * be reimplemented to use for example a Property.
# Line 252 | Line 395 | public class JSR166TestCase extends Test
395          return 50;
396      }
397  
255
398      /**
399       * Sets delays as multiples of SHORT_DELAY.
400       */
# Line 260 | Line 402 | public class JSR166TestCase extends Test
402          SHORT_DELAY_MS = getShortDelay();
403          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
404          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
405 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
405 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
406 >    }
407 >
408 >    /**
409 >     * Returns a timeout in milliseconds to be used in tests that
410 >     * verify that operations block or time out.
411 >     */
412 >    long timeoutMillis() {
413 >        return SHORT_DELAY_MS / 4;
414 >    }
415 >
416 >    /**
417 >     * Returns a new Date instance representing a time delayMillis
418 >     * milliseconds in the future.
419 >     */
420 >    Date delayedDate(long delayMillis) {
421 >        return new Date(System.currentTimeMillis() + delayMillis);
422      }
423  
424      /**
# Line 284 | Line 442 | public class JSR166TestCase extends Test
442      }
443  
444      /**
445 +     * Extra checks that get done for all test cases.
446 +     *
447       * Triggers test case failure if any thread assertions have failed,
448       * by rethrowing, in the test harness thread, any exception recorded
449       * earlier by threadRecordFailure.
450 +     *
451 +     * Triggers test case failure if interrupt status is set in the main thread.
452       */
453      public void tearDown() throws Exception {
454 <        Throwable t = threadFailure.getAndSet(null);
454 >        Throwable t = threadFailure.getAndSet(null);
455          if (t != null) {
456              if (t instanceof Error)
457                  throw (Error) t;
# Line 304 | Line 466 | public class JSR166TestCase extends Test
466                  throw afe;
467              }
468          }
469 +
470 +        if (Thread.interrupted())
471 +            throw new AssertionFailedError("interrupt status set in main thread");
472 +
473 +        checkForkJoinPoolThreadLeaks();
474 +    }
475 +
476 +    /**
477 +     * Finds missing try { ... } finally { joinPool(e); }
478 +     */
479 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
480 +        Thread[] survivors = new Thread[5];
481 +        int count = Thread.enumerate(survivors);
482 +        for (int i = 0; i < count; i++) {
483 +            Thread thread = survivors[i];
484 +            String name = thread.getName();
485 +            if (name.startsWith("ForkJoinPool-")) {
486 +                // give thread some time to terminate
487 +                thread.join(LONG_DELAY_MS);
488 +                if (!thread.isAlive()) continue;
489 +                thread.stop();
490 +                throw new AssertionFailedError
491 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
492 +                                   toString(), name));
493 +            }
494 +        }
495      }
496  
497      /**
# Line 384 | Line 572 | public class JSR166TestCase extends Test
572      public void threadAssertEquals(Object x, Object y) {
573          try {
574              assertEquals(x, y);
575 <        } catch (AssertionFailedError t) {
576 <            threadRecordFailure(t);
577 <            throw t;
578 <        } catch (Throwable t) {
579 <            threadUnexpectedException(t);
575 >        } catch (AssertionFailedError fail) {
576 >            threadRecordFailure(fail);
577 >            throw fail;
578 >        } catch (Throwable fail) {
579 >            threadUnexpectedException(fail);
580          }
581      }
582  
# Line 400 | Line 588 | public class JSR166TestCase extends Test
588      public void threadAssertSame(Object x, Object y) {
589          try {
590              assertSame(x, y);
591 <        } catch (AssertionFailedError t) {
592 <            threadRecordFailure(t);
593 <            throw t;
591 >        } catch (AssertionFailedError fail) {
592 >            threadRecordFailure(fail);
593 >            throw fail;
594          }
595      }
596  
# Line 435 | Line 623 | public class JSR166TestCase extends Test
623          else {
624              AssertionFailedError afe =
625                  new AssertionFailedError("unexpected exception: " + t);
626 <            t.initCause(t);
626 >            afe.initCause(t);
627              throw afe;
628          }
629      }
630  
631      /**
632 +     * Delays, via Thread.sleep, for the given millisecond delay, but
633 +     * if the sleep is shorter than specified, may re-sleep or yield
634 +     * until time elapses.
635 +     */
636 +    static void delay(long millis) throws InterruptedException {
637 +        long startTime = System.nanoTime();
638 +        long ns = millis * 1000 * 1000;
639 +        for (;;) {
640 +            if (millis > 0L)
641 +                Thread.sleep(millis);
642 +            else // too short to sleep
643 +                Thread.yield();
644 +            long d = ns - (System.nanoTime() - startTime);
645 +            if (d > 0L)
646 +                millis = d / (1000 * 1000);
647 +            else
648 +                break;
649 +        }
650 +    }
651 +
652 +    /**
653       * Waits out termination of a thread pool or fails doing so.
654       */
655 <    public void joinPool(ExecutorService exec) {
655 >    void joinPool(ExecutorService exec) {
656          try {
657              exec.shutdown();
658 <            assertTrue("ExecutorService did not terminate in a timely manner",
659 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
658 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
659 >                fail("ExecutorService " + exec +
660 >                     " did not terminate in a timely manner");
661          } catch (SecurityException ok) {
662              // Allowed in case test doesn't have privs
663 <        } catch (InterruptedException ie) {
663 >        } catch (InterruptedException fail) {
664 >            fail("Unexpected InterruptedException");
665 >        }
666 >    }
667 >
668 >    /**
669 >     * A debugging tool to print all stack traces, as jstack does.
670 >     */
671 >    static void printAllStackTraces() {
672 >        for (ThreadInfo info :
673 >                 ManagementFactory.getThreadMXBean()
674 >                 .dumpAllThreads(true, true))
675 >            System.err.print(info);
676 >    }
677 >
678 >    /**
679 >     * Checks that thread does not terminate within the default
680 >     * millisecond delay of {@code timeoutMillis()}.
681 >     */
682 >    void assertThreadStaysAlive(Thread thread) {
683 >        assertThreadStaysAlive(thread, timeoutMillis());
684 >    }
685 >
686 >    /**
687 >     * Checks that thread does not terminate within the given millisecond delay.
688 >     */
689 >    void assertThreadStaysAlive(Thread thread, long millis) {
690 >        try {
691 >            // No need to optimize the failing case via Thread.join.
692 >            delay(millis);
693 >            assertTrue(thread.isAlive());
694 >        } catch (InterruptedException fail) {
695 >            fail("Unexpected InterruptedException");
696 >        }
697 >    }
698 >
699 >    /**
700 >     * Checks that the threads do not terminate within the default
701 >     * millisecond delay of {@code timeoutMillis()}.
702 >     */
703 >    void assertThreadsStayAlive(Thread... threads) {
704 >        assertThreadsStayAlive(timeoutMillis(), threads);
705 >    }
706 >
707 >    /**
708 >     * Checks that the threads do not terminate within the given millisecond delay.
709 >     */
710 >    void assertThreadsStayAlive(long millis, Thread... threads) {
711 >        try {
712 >            // No need to optimize the failing case via Thread.join.
713 >            delay(millis);
714 >            for (Thread thread : threads)
715 >                assertTrue(thread.isAlive());
716 >        } catch (InterruptedException fail) {
717              fail("Unexpected InterruptedException");
718          }
719      }
720  
721 +    /**
722 +     * Checks that future.get times out, with the default timeout of
723 +     * {@code timeoutMillis()}.
724 +     */
725 +    void assertFutureTimesOut(Future future) {
726 +        assertFutureTimesOut(future, timeoutMillis());
727 +    }
728 +
729 +    /**
730 +     * Checks that future.get times out, with the given millisecond timeout.
731 +     */
732 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
733 +        long startTime = System.nanoTime();
734 +        try {
735 +            future.get(timeoutMillis, MILLISECONDS);
736 +            shouldThrow();
737 +        } catch (TimeoutException success) {
738 +        } catch (Exception fail) {
739 +            threadUnexpectedException(fail);
740 +        } finally { future.cancel(true); }
741 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
742 +    }
743  
744      /**
745       * Fails with message "should throw exception".
# Line 495 | Line 780 | public class JSR166TestCase extends Test
780      public static final Integer m6  = new Integer(-6);
781      public static final Integer m10 = new Integer(-10);
782  
498
783      /**
784       * Runs Runnable r with a security policy that permits precisely
785       * the specified permissions.  If there is no current security
# Line 507 | Line 791 | public class JSR166TestCase extends Test
791          SecurityManager sm = System.getSecurityManager();
792          if (sm == null) {
793              r.run();
794 +        }
795 +        runWithSecurityManagerWithPermissions(r, permissions);
796 +    }
797 +
798 +    /**
799 +     * Runs Runnable r with a security policy that permits precisely
800 +     * the specified permissions.  If there is no current security
801 +     * manager, a temporary one is set for the duration of the
802 +     * Runnable.  We require that any security manager permit
803 +     * getPolicy/setPolicy.
804 +     */
805 +    public void runWithSecurityManagerWithPermissions(Runnable r,
806 +                                                      Permission... permissions) {
807 +        SecurityManager sm = System.getSecurityManager();
808 +        if (sm == null) {
809              Policy savedPolicy = Policy.getPolicy();
810              try {
811                  Policy.setPolicy(permissivePolicy());
812                  System.setSecurityManager(new SecurityManager());
813 <                runWithPermissions(r, permissions);
813 >                runWithSecurityManagerWithPermissions(r, permissions);
814              } finally {
815                  System.setSecurityManager(null);
816                  Policy.setPolicy(savedPolicy);
# Line 559 | Line 858 | public class JSR166TestCase extends Test
858              return perms.implies(p);
859          }
860          public void refresh() {}
861 +        public String toString() {
862 +            List<Permission> ps = new ArrayList<Permission>();
863 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
864 +                ps.add(e.nextElement());
865 +            return "AdjustablePolicy with permissions " + ps;
866 +        }
867      }
868  
869      /**
# Line 586 | Line 891 | public class JSR166TestCase extends Test
891       */
892      void sleep(long millis) {
893          try {
894 <            Thread.sleep(millis);
895 <        } catch (InterruptedException ie) {
894 >            delay(millis);
895 >        } catch (InterruptedException fail) {
896              AssertionFailedError afe =
897                  new AssertionFailedError("Unexpected InterruptedException");
898 <            afe.initCause(ie);
898 >            afe.initCause(fail);
899              throw afe;
900          }
901      }
902  
903      /**
904 <     * Sleeps until the timeout has elapsed, or interrupted.
600 <     * Does <em>NOT</em> throw InterruptedException.
601 <     */
602 <    void sleepTillInterrupted(long timeoutMillis) {
603 <        try {
604 <            Thread.sleep(timeoutMillis);
605 <        } catch (InterruptedException wakeup) {}
606 <    }
607 <
608 <    /**
609 <     * Waits up to the specified number of milliseconds for the given
904 >     * Spin-waits up to the specified number of milliseconds for the given
905       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
906       */
907      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
908 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
614 <        long t0 = System.nanoTime();
908 >        long startTime = System.nanoTime();
909          for (;;) {
910              Thread.State s = thread.getState();
911              if (s == Thread.State.BLOCKED ||
# Line 620 | Line 914 | public class JSR166TestCase extends Test
914                  return;
915              else if (s == Thread.State.TERMINATED)
916                  fail("Unexpected thread termination");
917 <            else if (System.nanoTime() - t0 > timeoutNanos) {
917 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
918                  threadAssertTrue(thread.isAlive());
919                  return;
920              }
# Line 629 | Line 923 | public class JSR166TestCase extends Test
923      }
924  
925      /**
926 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
927 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
928 +     */
929 +    void waitForThreadToEnterWaitState(Thread thread) {
930 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
931 +    }
932 +
933 +    /**
934       * Returns the number of milliseconds since time given by
935       * startNanoTime, which must have been previously returned from a
936 <     * call to {@link System.nanoTime()}.
936 >     * call to {@link System#nanoTime()}.
937       */
938 <    long millisElapsedSince(long startNanoTime) {
938 >    static long millisElapsedSince(long startNanoTime) {
939          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
940      }
941  
942 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
943 + //         long startTime = System.nanoTime();
944 + //         try {
945 + //             r.run();
946 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
947 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
948 + //             throw new AssertionFailedError("did not return promptly");
949 + //     }
950 +
951 + //     void assertTerminatesPromptly(Runnable r) {
952 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
953 + //     }
954 +
955 +    /**
956 +     * Checks that timed f.get() returns the expected value, and does not
957 +     * wait for the timeout to elapse before returning.
958 +     */
959 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
960 +        long startTime = System.nanoTime();
961 +        try {
962 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
963 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
964 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
965 +            throw new AssertionFailedError("timed get did not return promptly");
966 +    }
967 +
968 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
969 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
970 +    }
971 +
972      /**
973       * Returns a new started daemon Thread running the given runnable.
974       */
# Line 655 | Line 987 | public class JSR166TestCase extends Test
987      void awaitTermination(Thread t, long timeoutMillis) {
988          try {
989              t.join(timeoutMillis);
990 <        } catch (InterruptedException ie) {
991 <            threadUnexpectedException(ie);
990 >        } catch (InterruptedException fail) {
991 >            threadUnexpectedException(fail);
992          } finally {
993 <            if (t.isAlive()) {
993 >            if (t.getState() != Thread.State.TERMINATED) {
994                  t.interrupt();
995                  fail("Test timed out");
996              }
997          }
998      }
999  
1000 +    /**
1001 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1002 +     * terminate (using {@link Thread#join(long)}), else interrupts
1003 +     * the thread (in the hope that it may terminate later) and fails.
1004 +     */
1005 +    void awaitTermination(Thread t) {
1006 +        awaitTermination(t, LONG_DELAY_MS);
1007 +    }
1008 +
1009      // Some convenient Runnable classes
1010  
1011      public abstract class CheckedRunnable implements Runnable {
# Line 673 | Line 1014 | public class JSR166TestCase extends Test
1014          public final void run() {
1015              try {
1016                  realRun();
1017 <            } catch (Throwable t) {
1018 <                threadUnexpectedException(t);
1017 >            } catch (Throwable fail) {
1018 >                threadUnexpectedException(fail);
1019              }
1020          }
1021      }
# Line 727 | Line 1068 | public class JSR166TestCase extends Test
1068                  realRun();
1069                  threadShouldThrow("InterruptedException");
1070              } catch (InterruptedException success) {
1071 <            } catch (Throwable t) {
1072 <                threadUnexpectedException(t);
1071 >                threadAssertFalse(Thread.interrupted());
1072 >            } catch (Throwable fail) {
1073 >                threadUnexpectedException(fail);
1074              }
1075          }
1076      }
# Line 739 | Line 1081 | public class JSR166TestCase extends Test
1081          public final T call() {
1082              try {
1083                  return realCall();
1084 <            } catch (Throwable t) {
1085 <                threadUnexpectedException(t);
1084 >            } catch (Throwable fail) {
1085 >                threadUnexpectedException(fail);
1086                  return null;
1087              }
1088          }
# Line 756 | Line 1098 | public class JSR166TestCase extends Test
1098                  threadShouldThrow("InterruptedException");
1099                  return result;
1100              } catch (InterruptedException success) {
1101 <            } catch (Throwable t) {
1102 <                threadUnexpectedException(t);
1101 >                threadAssertFalse(Thread.interrupted());
1102 >            } catch (Throwable fail) {
1103 >                threadUnexpectedException(fail);
1104              }
1105              return null;
1106          }
# Line 787 | Line 1130 | public class JSR166TestCase extends Test
1130              }};
1131      }
1132  
1133 +    public Runnable awaiter(final CountDownLatch latch) {
1134 +        return new CheckedRunnable() {
1135 +            public void realRun() throws InterruptedException {
1136 +                await(latch);
1137 +            }};
1138 +    }
1139 +
1140 +    public void await(CountDownLatch latch) {
1141 +        try {
1142 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1143 +        } catch (Throwable fail) {
1144 +            threadUnexpectedException(fail);
1145 +        }
1146 +    }
1147 +
1148 +    public void await(Semaphore semaphore) {
1149 +        try {
1150 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1151 +        } catch (Throwable fail) {
1152 +            threadUnexpectedException(fail);
1153 +        }
1154 +    }
1155 +
1156 + //     /**
1157 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1158 + //      */
1159 + //     public void await(AtomicBoolean flag) {
1160 + //         await(flag, LONG_DELAY_MS);
1161 + //     }
1162 +
1163 + //     /**
1164 + //      * Spin-waits up to the specified timeout until flag becomes true.
1165 + //      */
1166 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1167 + //         long startTime = System.nanoTime();
1168 + //         while (!flag.get()) {
1169 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1170 + //                 throw new AssertionFailedError("timed out");
1171 + //             Thread.yield();
1172 + //         }
1173 + //     }
1174 +
1175      public static class NPETask implements Callable<String> {
1176          public String call() { throw new NullPointerException(); }
1177      }
# Line 797 | Line 1182 | public class JSR166TestCase extends Test
1182  
1183      public class ShortRunnable extends CheckedRunnable {
1184          protected void realRun() throws Throwable {
1185 <            Thread.sleep(SHORT_DELAY_MS);
1185 >            delay(SHORT_DELAY_MS);
1186          }
1187      }
1188  
1189      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1190          protected void realRun() throws InterruptedException {
1191 <            Thread.sleep(SHORT_DELAY_MS);
1191 >            delay(SHORT_DELAY_MS);
1192          }
1193      }
1194  
1195      public class SmallRunnable extends CheckedRunnable {
1196          protected void realRun() throws Throwable {
1197 <            Thread.sleep(SMALL_DELAY_MS);
1197 >            delay(SMALL_DELAY_MS);
1198          }
1199      }
1200  
1201      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1202          protected void realRun() {
1203              try {
1204 <                Thread.sleep(SMALL_DELAY_MS);
1204 >                delay(SMALL_DELAY_MS);
1205              } catch (InterruptedException ok) {}
1206          }
1207      }
1208  
1209      public class SmallCallable extends CheckedCallable {
1210          protected Object realCall() throws InterruptedException {
1211 <            Thread.sleep(SMALL_DELAY_MS);
1211 >            delay(SMALL_DELAY_MS);
1212              return Boolean.TRUE;
1213          }
1214      }
1215  
1216      public class MediumRunnable extends CheckedRunnable {
1217          protected void realRun() throws Throwable {
1218 <            Thread.sleep(MEDIUM_DELAY_MS);
1218 >            delay(MEDIUM_DELAY_MS);
1219          }
1220      }
1221  
1222      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1223          protected void realRun() throws InterruptedException {
1224 <            Thread.sleep(MEDIUM_DELAY_MS);
1224 >            delay(MEDIUM_DELAY_MS);
1225          }
1226      }
1227  
# Line 844 | Line 1229 | public class JSR166TestCase extends Test
1229          return new CheckedRunnable() {
1230              protected void realRun() {
1231                  try {
1232 <                    Thread.sleep(timeoutMillis);
1232 >                    delay(timeoutMillis);
1233                  } catch (InterruptedException ok) {}
1234              }};
1235      }
# Line 852 | Line 1237 | public class JSR166TestCase extends Test
1237      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1238          protected void realRun() {
1239              try {
1240 <                Thread.sleep(MEDIUM_DELAY_MS);
1240 >                delay(MEDIUM_DELAY_MS);
1241              } catch (InterruptedException ok) {}
1242          }
1243      }
# Line 860 | Line 1245 | public class JSR166TestCase extends Test
1245      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1246          protected void realRun() {
1247              try {
1248 <                Thread.sleep(LONG_DELAY_MS);
1248 >                delay(LONG_DELAY_MS);
1249              } catch (InterruptedException ok) {}
1250          }
1251      }
# Line 884 | Line 1269 | public class JSR166TestCase extends Test
1269                  public boolean isDone() { return done; }
1270                  public void run() {
1271                      try {
1272 <                        Thread.sleep(timeoutMillis);
1272 >                        delay(timeoutMillis);
1273                          done = true;
1274                      } catch (InterruptedException ok) {}
1275                  }
# Line 895 | Line 1280 | public class JSR166TestCase extends Test
1280          public volatile boolean done = false;
1281          public void run() {
1282              try {
1283 <                Thread.sleep(SHORT_DELAY_MS);
1283 >                delay(SHORT_DELAY_MS);
1284                  done = true;
1285              } catch (InterruptedException ok) {}
1286          }
# Line 905 | Line 1290 | public class JSR166TestCase extends Test
1290          public volatile boolean done = false;
1291          public void run() {
1292              try {
1293 <                Thread.sleep(SMALL_DELAY_MS);
1293 >                delay(SMALL_DELAY_MS);
1294                  done = true;
1295              } catch (InterruptedException ok) {}
1296          }
# Line 915 | Line 1300 | public class JSR166TestCase extends Test
1300          public volatile boolean done = false;
1301          public void run() {
1302              try {
1303 <                Thread.sleep(MEDIUM_DELAY_MS);
1303 >                delay(MEDIUM_DELAY_MS);
1304                  done = true;
1305              } catch (InterruptedException ok) {}
1306          }
# Line 925 | Line 1310 | public class JSR166TestCase extends Test
1310          public volatile boolean done = false;
1311          public void run() {
1312              try {
1313 <                Thread.sleep(LONG_DELAY_MS);
1313 >                delay(LONG_DELAY_MS);
1314                  done = true;
1315              } catch (InterruptedException ok) {}
1316          }
# Line 942 | Line 1327 | public class JSR166TestCase extends Test
1327          public volatile boolean done = false;
1328          public Object call() {
1329              try {
1330 <                Thread.sleep(SMALL_DELAY_MS);
1330 >                delay(SMALL_DELAY_MS);
1331                  done = true;
1332              } catch (InterruptedException ok) {}
1333              return Boolean.TRUE;
# Line 955 | Line 1340 | public class JSR166TestCase extends Test
1340      public abstract class CheckedRecursiveAction extends RecursiveAction {
1341          protected abstract void realCompute() throws Throwable;
1342  
1343 <        public final void compute() {
1343 >        @Override protected final void compute() {
1344              try {
1345                  realCompute();
1346 <            } catch (Throwable t) {
1347 <                threadUnexpectedException(t);
1346 >            } catch (Throwable fail) {
1347 >                threadUnexpectedException(fail);
1348              }
1349          }
1350      }
# Line 970 | Line 1355 | public class JSR166TestCase extends Test
1355      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1356          protected abstract T realCompute() throws Throwable;
1357  
1358 <        public final T compute() {
1358 >        @Override protected final T compute() {
1359              try {
1360                  return realCompute();
1361 <            } catch (Throwable t) {
1362 <                threadUnexpectedException(t);
1361 >            } catch (Throwable fail) {
1362 >                threadUnexpectedException(fail);
1363                  return null;
1364              }
1365          }
# Line 989 | Line 1374 | public class JSR166TestCase extends Test
1374      }
1375  
1376      /**
1377 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1378 <     * of throwing checked exceptions.
1377 >     * A CyclicBarrier that uses timed await and fails with
1378 >     * AssertionFailedErrors instead of throwing checked exceptions.
1379       */
1380      public class CheckedBarrier extends CyclicBarrier {
1381          public CheckedBarrier(int parties) { super(parties); }
1382  
1383          public int await() {
1384              try {
1385 <                return super.await();
1386 <            } catch (Exception e) {
1385 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1386 >            } catch (TimeoutException timedOut) {
1387 >                throw new AssertionFailedError("timed out");
1388 >            } catch (Exception fail) {
1389                  AssertionFailedError afe =
1390 <                    new AssertionFailedError("Unexpected exception: " + e);
1391 <                afe.initCause(e);
1390 >                    new AssertionFailedError("Unexpected exception: " + fail);
1391 >                afe.initCause(fail);
1392                  throw afe;
1393              }
1394          }
1395      }
1396  
1397 +    void checkEmpty(BlockingQueue q) {
1398 +        try {
1399 +            assertTrue(q.isEmpty());
1400 +            assertEquals(0, q.size());
1401 +            assertNull(q.peek());
1402 +            assertNull(q.poll());
1403 +            assertNull(q.poll(0, MILLISECONDS));
1404 +            assertEquals(q.toString(), "[]");
1405 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1406 +            assertFalse(q.iterator().hasNext());
1407 +            try {
1408 +                q.element();
1409 +                shouldThrow();
1410 +            } catch (NoSuchElementException success) {}
1411 +            try {
1412 +                q.iterator().next();
1413 +                shouldThrow();
1414 +            } catch (NoSuchElementException success) {}
1415 +            try {
1416 +                q.remove();
1417 +                shouldThrow();
1418 +            } catch (NoSuchElementException success) {}
1419 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1420 +    }
1421 +
1422 +    void assertSerialEquals(Object x, Object y) {
1423 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1424 +    }
1425 +
1426 +    void assertNotSerialEquals(Object x, Object y) {
1427 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1428 +    }
1429 +
1430 +    byte[] serialBytes(Object o) {
1431 +        try {
1432 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1433 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1434 +            oos.writeObject(o);
1435 +            oos.flush();
1436 +            oos.close();
1437 +            return bos.toByteArray();
1438 +        } catch (Throwable fail) {
1439 +            threadUnexpectedException(fail);
1440 +            return new byte[0];
1441 +        }
1442 +    }
1443 +
1444 +    @SuppressWarnings("unchecked")
1445 +    <T> T serialClone(T o) {
1446 +        try {
1447 +            ObjectInputStream ois = new ObjectInputStream
1448 +                (new ByteArrayInputStream(serialBytes(o)));
1449 +            T clone = (T) ois.readObject();
1450 +            assertSame(o.getClass(), clone.getClass());
1451 +            return clone;
1452 +        } catch (Throwable fail) {
1453 +            threadUnexpectedException(fail);
1454 +            return null;
1455 +        }
1456 +    }
1457 +
1458 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1459 +                             Runnable... throwingActions) {
1460 +        for (Runnable throwingAction : throwingActions) {
1461 +            boolean threw = false;
1462 +            try { throwingAction.run(); }
1463 +            catch (Throwable t) {
1464 +                threw = true;
1465 +                if (!expectedExceptionClass.isInstance(t)) {
1466 +                    AssertionFailedError afe =
1467 +                        new AssertionFailedError
1468 +                        ("Expected " + expectedExceptionClass.getName() +
1469 +                         ", got " + t.getClass().getName());
1470 +                    afe.initCause(t);
1471 +                    threadUnexpectedException(afe);
1472 +                }
1473 +            }
1474 +            if (!threw)
1475 +                shouldThrow(expectedExceptionClass.getName());
1476 +        }
1477 +    }
1478 +
1479 +    public void assertIteratorExhausted(Iterator<?> it) {
1480 +        try {
1481 +            it.next();
1482 +            shouldThrow();
1483 +        } catch (NoSuchElementException success) {}
1484 +        assertFalse(it.hasNext());
1485 +    }
1486   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines