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.43 by jsr166, Sat Nov 21 10:25:05 2009 UTC vs.
Revision 1.121 by jsr166, Wed Jul 9 16:51:40 2014 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.*;
10 > import java.io.ByteArrayInputStream;
11 > import java.io.ByteArrayOutputStream;
12 > import java.io.ObjectInputStream;
13 > import java.io.ObjectOutputStream;
14 > import java.lang.management.ManagementFactory;
15 > import java.lang.management.ThreadInfo;
16 > import java.lang.reflect.Method;
17 > import java.util.ArrayList;
18 > import java.util.Arrays;
19 > import java.util.Date;
20 > import java.util.Enumeration;
21 > import java.util.List;
22 > import java.util.NoSuchElementException;
23 > import java.util.PropertyPermission;
24   import java.util.concurrent.*;
25 + import java.util.concurrent.atomic.AtomicBoolean;
26 + import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 < import java.io.*;
29 < import java.security.*;
28 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
29 > import java.util.regex.Pattern;
30 > import java.security.CodeSource;
31 > import java.security.Permission;
32 > import java.security.PermissionCollection;
33 > import java.security.Permissions;
34 > import java.security.Policy;
35 > import java.security.ProtectionDomain;
36 > import java.security.SecurityPermission;
37  
38   /**
39   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 26 | Line 48 | import java.security.*;
48   * <li> All assertions in code running in generated threads must use
49   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
50   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
51 < * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
51 > * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
52   * particularly recommended) for other code to use these forms too.
53   * Only the most typically used JUnit assertion methods are defined
54   * this way, but enough to live with.</li>
55   *
56   * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
57 < * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
57 > * to invoke {@code super.setUp} and {@code super.tearDown} within
58   * them. These methods are used to clear and check for thread
59   * assertion failures.</li>
60   *
61 < * <li>All delays and timeouts must use one of the constants <tt>
62 < * SHORT_DELAY_MS</tt>, <tt> SMALL_DELAY_MS</tt>, <tt> MEDIUM_DELAY_MS</tt>,
63 < * <tt> LONG_DELAY_MS</tt>. The idea here is that a SHORT is always
61 > * <li>All delays and timeouts must use one of the constants {@code
62 > * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
63 > * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
64   * discriminable from zero time, and always allows enough time for the
65   * small amounts of computation (creating a thread, calling a few
66   * methods, etc) needed to reach a timeout point. Similarly, a SMALL
# Line 48 | Line 70 | import java.security.*;
70   * in one spot to rerun tests on slower platforms.</li>
71   *
72   * <li> All threads generated must be joined inside each test case
73 < * method (or <tt>fail</tt> to do so) before returning from the
74 < * method. The <tt> joinPool</tt> method can be used to do this when
73 > * method (or {@code fail} to do so) before returning from the
74 > * method. The {@code joinPool} method can be used to do this when
75   * using Executors.</li>
76   *
77   * </ol>
78   *
79 < * <p> <b>Other notes</b>
79 > * <p><b>Other notes</b>
80   * <ul>
81   *
82   * <li> Usually, there is one testcase method per JSR166 method
# Line 81 | Line 103 | import java.security.*;
103   * any particular package to simplify things for people integrating
104   * them in TCK test suites.</li>
105   *
106 < * <li> As a convenience, the <tt>main</tt> of this class (JSR166TestCase)
106 > * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
107   * runs all JSR166 unit tests.</li>
108   *
109   * </ul>
110   */
111   public class JSR166TestCase extends TestCase {
112 +    private static final boolean useSecurityManager =
113 +        Boolean.getBoolean("jsr166.useSecurityManager");
114 +
115 +    protected static final boolean expensiveTests =
116 +        Boolean.getBoolean("jsr166.expensiveTests");
117 +
118 +    /**
119 +     * If true, also run tests that are not part of the official tck
120 +     * because they test unspecified implementation details.
121 +     */
122 +    protected static final boolean testImplementationDetails =
123 +        Boolean.getBoolean("jsr166.testImplementationDetails");
124 +
125 +    /**
126 +     * If true, report on stdout all "slow" tests, that is, ones that
127 +     * take more than profileThreshold milliseconds to execute.
128 +     */
129 +    private static final boolean profileTests =
130 +        Boolean.getBoolean("jsr166.profileTests");
131 +
132 +    /**
133 +     * The number of milliseconds that tests are permitted for
134 +     * execution without being reported, when profileTests is set.
135 +     */
136 +    private static final long profileThreshold =
137 +        Long.getLong("jsr166.profileThreshold", 100);
138 +
139 +    /**
140 +     * The number of repetitions per test (for tickling rare bugs).
141 +     */
142 +    private static final int runsPerTest =
143 +        Integer.getInteger("jsr166.runsPerTest", 1);
144 +
145 +    /**
146 +     * A filter for tests to run, matching strings of the form
147 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
148 +     * Usefully combined with jsr166.runsPerTest.
149 +     */
150 +    private static final Pattern methodFilter = methodFilter();
151 +
152 +    private static Pattern methodFilter() {
153 +        String regex = System.getProperty("jsr166.methodFilter");
154 +        return (regex == null) ? null : Pattern.compile(regex);
155 +    }
156 +
157 +    protected void runTest() throws Throwable {
158 +        if (methodFilter == null
159 +            || methodFilter.matcher(toString()).find()) {
160 +            for (int i = 0; i < runsPerTest; i++) {
161 +                if (profileTests)
162 +                    runTestProfiled();
163 +                else
164 +                    super.runTest();
165 +            }
166 +        }
167 +    }
168 +
169 +    protected void runTestProfiled() throws Throwable {
170 +        // Warmup run, notably to trigger all needed classloading.
171 +        super.runTest();
172 +        long t0 = System.nanoTime();
173 +        try {
174 +            super.runTest();
175 +        } finally {
176 +            long elapsedMillis = millisElapsedSince(t0);
177 +            if (elapsedMillis >= profileThreshold)
178 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
179 +        }
180 +    }
181 +
182      /**
183 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
183 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
184 >     * Optional command line arg provides the number of iterations to
185 >     * repeat running the tests.
186       */
187      public static void main(String[] args) {
188 <        int iters = 1;
189 <        if (args.length > 0)
190 <            iters = Integer.parseInt(args[0]);
188 >        if (useSecurityManager) {
189 >            System.err.println("Setting a permissive security manager");
190 >            Policy.setPolicy(permissivePolicy());
191 >            System.setSecurityManager(new SecurityManager());
192 >        }
193 >        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
194 >
195          Test s = suite();
196          for (int i = 0; i < iters; ++i) {
197              junit.textui.TestRunner.run(s);
# Line 103 | Line 201 | public class JSR166TestCase extends Test
201          System.exit(0);
202      }
203  
204 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
205 +        TestSuite suite = new TestSuite();
206 +        for (Object suiteOrClass : suiteOrClasses) {
207 +            if (suiteOrClass instanceof TestSuite)
208 +                suite.addTest((TestSuite) suiteOrClass);
209 +            else if (suiteOrClass instanceof Class)
210 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
211 +            else
212 +                throw new ClassCastException("not a test suite or class");
213 +        }
214 +        return suite;
215 +    }
216 +
217 +    public static void addNamedTestClasses(TestSuite suite,
218 +                                           String... testClassNames) {
219 +        for (String testClassName : testClassNames) {
220 +            try {
221 +                Class<?> testClass = Class.forName(testClassName);
222 +                Method m = testClass.getDeclaredMethod("suite",
223 +                                                       new Class<?>[0]);
224 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
225 +            } catch (Exception e) {
226 +                throw new Error("Missing test class", e);
227 +            }
228 +        }
229 +    }
230 +
231 +    public static final double JAVA_CLASS_VERSION;
232 +    public static final String JAVA_SPECIFICATION_VERSION;
233 +    static {
234 +        try {
235 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
236 +                new java.security.PrivilegedAction<Double>() {
237 +                public Double run() {
238 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
239 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
240 +                new java.security.PrivilegedAction<String>() {
241 +                public String run() {
242 +                    return System.getProperty("java.specification.version");}});
243 +        } catch (Throwable t) {
244 +            throw new Error(t);
245 +        }
246 +    }
247 +
248 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
249 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
250 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
251 +    public static boolean atLeastJava9() {
252 +        // As of 2014-05, java9 still uses 52.0 class file version
253 +        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
254 +    }
255 +
256      /**
257 <     * Collects all JSR166 unit tests as one suite
257 >     * Collects all JSR166 unit tests as one suite.
258       */
259      public static Test suite() {
260 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
261 <
262 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
263 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
264 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
265 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
266 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
267 <        suite.addTest(new TestSuite(PhaserTest.class));
268 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
269 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
270 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
271 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
272 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
273 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
274 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
275 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
276 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
277 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
278 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
279 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
280 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
281 <        suite.addTest(new TestSuite(AtomicLongTest.class));
282 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
283 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
284 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
285 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
286 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
287 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
288 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
289 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
290 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
291 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
292 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
293 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
294 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
295 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
296 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
297 <        suite.addTest(new TestSuite(DelayQueueTest.class));
298 <        suite.addTest(new TestSuite(EntryTest.class));
299 <        suite.addTest(new TestSuite(ExchangerTest.class));
300 <        suite.addTest(new TestSuite(ExecutorsTest.class));
301 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
302 <        suite.addTest(new TestSuite(FutureTaskTest.class));
303 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
304 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
305 <        suite.addTest(new TestSuite(LinkedListTest.class));
306 <        suite.addTest(new TestSuite(LockSupportTest.class));
307 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
308 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
309 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
310 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
311 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
312 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
313 <        suite.addTest(new TestSuite(SemaphoreTest.class));
314 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
315 <        suite.addTest(new TestSuite(SystemTest.class));
316 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
317 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
318 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
319 <        suite.addTest(new TestSuite(ThreadTest.class));
320 <        suite.addTest(new TestSuite(TimeUnitTest.class));
321 <        suite.addTest(new TestSuite(TreeMapTest.class));
322 <        suite.addTest(new TestSuite(TreeSetTest.class));
323 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
324 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
260 >        // Java7+ test classes
261 >        TestSuite suite = newTestSuite(
262 >            ForkJoinPoolTest.suite(),
263 >            ForkJoinTaskTest.suite(),
264 >            RecursiveActionTest.suite(),
265 >            RecursiveTaskTest.suite(),
266 >            LinkedTransferQueueTest.suite(),
267 >            PhaserTest.suite(),
268 >            ThreadLocalRandomTest.suite(),
269 >            AbstractExecutorServiceTest.suite(),
270 >            AbstractQueueTest.suite(),
271 >            AbstractQueuedSynchronizerTest.suite(),
272 >            AbstractQueuedLongSynchronizerTest.suite(),
273 >            ArrayBlockingQueueTest.suite(),
274 >            ArrayDequeTest.suite(),
275 >            AtomicBooleanTest.suite(),
276 >            AtomicIntegerArrayTest.suite(),
277 >            AtomicIntegerFieldUpdaterTest.suite(),
278 >            AtomicIntegerTest.suite(),
279 >            AtomicLongArrayTest.suite(),
280 >            AtomicLongFieldUpdaterTest.suite(),
281 >            AtomicLongTest.suite(),
282 >            AtomicMarkableReferenceTest.suite(),
283 >            AtomicReferenceArrayTest.suite(),
284 >            AtomicReferenceFieldUpdaterTest.suite(),
285 >            AtomicReferenceTest.suite(),
286 >            AtomicStampedReferenceTest.suite(),
287 >            ConcurrentHashMapTest.suite(),
288 >            ConcurrentLinkedDequeTest.suite(),
289 >            ConcurrentLinkedQueueTest.suite(),
290 >            ConcurrentSkipListMapTest.suite(),
291 >            ConcurrentSkipListSubMapTest.suite(),
292 >            ConcurrentSkipListSetTest.suite(),
293 >            ConcurrentSkipListSubSetTest.suite(),
294 >            CopyOnWriteArrayListTest.suite(),
295 >            CopyOnWriteArraySetTest.suite(),
296 >            CountDownLatchTest.suite(),
297 >            CyclicBarrierTest.suite(),
298 >            DelayQueueTest.suite(),
299 >            EntryTest.suite(),
300 >            ExchangerTest.suite(),
301 >            ExecutorsTest.suite(),
302 >            ExecutorCompletionServiceTest.suite(),
303 >            FutureTaskTest.suite(),
304 >            LinkedBlockingDequeTest.suite(),
305 >            LinkedBlockingQueueTest.suite(),
306 >            LinkedListTest.suite(),
307 >            LockSupportTest.suite(),
308 >            PriorityBlockingQueueTest.suite(),
309 >            PriorityQueueTest.suite(),
310 >            ReentrantLockTest.suite(),
311 >            ReentrantReadWriteLockTest.suite(),
312 >            ScheduledExecutorTest.suite(),
313 >            ScheduledExecutorSubclassTest.suite(),
314 >            SemaphoreTest.suite(),
315 >            SynchronousQueueTest.suite(),
316 >            SystemTest.suite(),
317 >            ThreadLocalTest.suite(),
318 >            ThreadPoolExecutorTest.suite(),
319 >            ThreadPoolExecutorSubclassTest.suite(),
320 >            ThreadTest.suite(),
321 >            TimeUnitTest.suite(),
322 >            TreeMapTest.suite(),
323 >            TreeSetTest.suite(),
324 >            TreeSubMapTest.suite(),
325 >            TreeSubSetTest.suite());
326 >
327 >        // Java8+ test classes
328 >        if (atLeastJava8()) {
329 >            String[] java8TestClassNames = {
330 >                "Atomic8Test",
331 >                "CompletableFutureTest",
332 >                "ConcurrentHashMap8Test",
333 >                "CountedCompleterTest",
334 >                "DoubleAccumulatorTest",
335 >                "DoubleAdderTest",
336 >                "ForkJoinPool8Test",
337 >                "ForkJoinTask8Test",
338 >                "LongAccumulatorTest",
339 >                "LongAdderTest",
340 >                "SplittableRandomTest",
341 >                "StampedLockTest",
342 >                "ThreadLocalRandom8Test",
343 >            };
344 >            addNamedTestClasses(suite, java8TestClassNames);
345 >        }
346 >
347 >        // Java9+ test classes
348 >        if (atLeastJava9()) {
349 >            String[] java9TestClassNames = {
350 >                "ThreadPoolExecutor9Test",
351 >            };
352 >            addNamedTestClasses(suite, java9TestClassNames);
353 >        }
354  
355          return suite;
356      }
357  
358 +    // Delays for timing-dependent tests, in milliseconds.
359  
360      public static long SHORT_DELAY_MS;
361      public static long SMALL_DELAY_MS;
362      public static long MEDIUM_DELAY_MS;
363      public static long LONG_DELAY_MS;
364  
185
365      /**
366       * Returns the shortest timed delay. This could
367       * be reimplemented to use for example a Property.
# Line 191 | Line 370 | public class JSR166TestCase extends Test
370          return 50;
371      }
372  
194
373      /**
374       * Sets delays as multiples of SHORT_DELAY.
375       */
376      protected void setDelays() {
377          SHORT_DELAY_MS = getShortDelay();
378 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
378 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
379          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
380 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
380 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
381      }
382  
383      /**
384 <     * Flag set true if any threadAssert methods fail
384 >     * Returns a timeout in milliseconds to be used in tests that
385 >     * verify that operations block or time out.
386       */
387 <    volatile boolean threadFailed;
387 >    long timeoutMillis() {
388 >        return SHORT_DELAY_MS / 4;
389 >    }
390 >
391 >    /**
392 >     * Returns a new Date instance representing a time delayMillis
393 >     * milliseconds in the future.
394 >     */
395 >    Date delayedDate(long delayMillis) {
396 >        return new Date(System.currentTimeMillis() + delayMillis);
397 >    }
398 >
399 >    /**
400 >     * The first exception encountered if any threadAssertXXX method fails.
401 >     */
402 >    private final AtomicReference<Throwable> threadFailure
403 >        = new AtomicReference<Throwable>(null);
404  
405      /**
406 <     * Initializes test to indicate that no thread assertions have failed
406 >     * Records an exception so that it can be rethrown later in the test
407 >     * harness thread, triggering a test case failure.  Only the first
408 >     * failure is recorded; subsequent calls to this method from within
409 >     * the same test have no effect.
410       */
411 +    public void threadRecordFailure(Throwable t) {
412 +        threadFailure.compareAndSet(null, t);
413 +    }
414 +
415      public void setUp() {
416          setDelays();
215        threadFailed = false;
417      }
418  
419      /**
420 <     * Triggers test case failure if any thread assertions have failed
420 >     * Extra checks that get done for all test cases.
421 >     *
422 >     * Triggers test case failure if any thread assertions have failed,
423 >     * by rethrowing, in the test harness thread, any exception recorded
424 >     * earlier by threadRecordFailure.
425 >     *
426 >     * Triggers test case failure if interrupt status is set in the main thread.
427 >     */
428 >    public void tearDown() throws Exception {
429 >        Throwable t = threadFailure.getAndSet(null);
430 >        if (t != null) {
431 >            if (t instanceof Error)
432 >                throw (Error) t;
433 >            else if (t instanceof RuntimeException)
434 >                throw (RuntimeException) t;
435 >            else if (t instanceof Exception)
436 >                throw (Exception) t;
437 >            else {
438 >                AssertionFailedError afe =
439 >                    new AssertionFailedError(t.toString());
440 >                afe.initCause(t);
441 >                throw afe;
442 >            }
443 >        }
444 >
445 >        if (Thread.interrupted())
446 >            throw new AssertionFailedError("interrupt status set in main thread");
447 >
448 >        checkForkJoinPoolThreadLeaks();
449 >    }
450 >
451 >    /**
452 >     * Find missing try { ... } finally { joinPool(e); }
453       */
454 <    public void tearDown() {
455 <        assertFalse(threadFailed);
454 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
455 >        Thread[] survivors = new Thread[5];
456 >        int count = Thread.enumerate(survivors);
457 >        for (int i = 0; i < count; i++) {
458 >            Thread thread = survivors[i];
459 >            String name = thread.getName();
460 >            if (name.startsWith("ForkJoinPool-")) {
461 >                // give thread some time to terminate
462 >                thread.join(LONG_DELAY_MS);
463 >                if (!thread.isAlive()) continue;
464 >                thread.stop();
465 >                throw new AssertionFailedError
466 >                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
467 >                                   toString(), name));
468 >            }
469 >        }
470      }
471  
472      /**
473 <     * Fail, also setting status to indicate current testcase should fail
473 >     * Just like fail(reason), but additionally recording (using
474 >     * threadRecordFailure) any AssertionFailedError thrown, so that
475 >     * the current testcase will fail.
476       */
477      public void threadFail(String reason) {
478 <        threadFailed = true;
479 <        fail(reason);
478 >        try {
479 >            fail(reason);
480 >        } catch (AssertionFailedError t) {
481 >            threadRecordFailure(t);
482 >            fail(reason);
483 >        }
484      }
485  
486      /**
487 <     * If expression not true, set status to indicate current testcase
488 <     * should fail
487 >     * Just like assertTrue(b), but additionally recording (using
488 >     * threadRecordFailure) any AssertionFailedError thrown, so that
489 >     * the current testcase will fail.
490       */
491      public void threadAssertTrue(boolean b) {
492 <        if (!b) {
239 <            threadFailed = true;
492 >        try {
493              assertTrue(b);
494 +        } catch (AssertionFailedError t) {
495 +            threadRecordFailure(t);
496 +            throw t;
497          }
498      }
499  
500      /**
501 <     * If expression not false, set status to indicate current testcase
502 <     * should fail
501 >     * Just like assertFalse(b), but additionally recording (using
502 >     * threadRecordFailure) any AssertionFailedError thrown, so that
503 >     * the current testcase will fail.
504       */
505      public void threadAssertFalse(boolean b) {
506 <        if (b) {
250 <            threadFailed = true;
506 >        try {
507              assertFalse(b);
508 +        } catch (AssertionFailedError t) {
509 +            threadRecordFailure(t);
510 +            throw t;
511          }
512      }
513  
514      /**
515 <     * If argument not null, set status to indicate current testcase
516 <     * should fail
515 >     * Just like assertNull(x), but additionally recording (using
516 >     * threadRecordFailure) any AssertionFailedError thrown, so that
517 >     * the current testcase will fail.
518       */
519      public void threadAssertNull(Object x) {
520 <        if (x != null) {
261 <            threadFailed = true;
520 >        try {
521              assertNull(x);
522 +        } catch (AssertionFailedError t) {
523 +            threadRecordFailure(t);
524 +            throw t;
525          }
526      }
527  
528      /**
529 <     * If arguments not equal, set status to indicate current testcase
530 <     * should fail
529 >     * Just like assertEquals(x, y), but additionally recording (using
530 >     * threadRecordFailure) any AssertionFailedError thrown, so that
531 >     * the current testcase will fail.
532       */
533      public void threadAssertEquals(long x, long y) {
534 <        if (x != y) {
272 <            threadFailed = true;
534 >        try {
535              assertEquals(x, y);
536 +        } catch (AssertionFailedError t) {
537 +            threadRecordFailure(t);
538 +            throw t;
539          }
540      }
541  
542      /**
543 <     * If arguments not equal, set status to indicate current testcase
544 <     * should fail
543 >     * Just like assertEquals(x, y), but additionally recording (using
544 >     * threadRecordFailure) any AssertionFailedError thrown, so that
545 >     * the current testcase will fail.
546       */
547      public void threadAssertEquals(Object x, Object y) {
548 <        if (x != y && (x == null || !x.equals(y))) {
283 <            threadFailed = true;
548 >        try {
549              assertEquals(x, y);
550 +        } catch (AssertionFailedError t) {
551 +            threadRecordFailure(t);
552 +            throw t;
553 +        } catch (Throwable t) {
554 +            threadUnexpectedException(t);
555 +        }
556 +    }
557 +
558 +    /**
559 +     * Just like assertSame(x, y), but additionally recording (using
560 +     * threadRecordFailure) any AssertionFailedError thrown, so that
561 +     * the current testcase will fail.
562 +     */
563 +    public void threadAssertSame(Object x, Object y) {
564 +        try {
565 +            assertSame(x, y);
566 +        } catch (AssertionFailedError t) {
567 +            threadRecordFailure(t);
568 +            throw t;
569          }
570      }
571  
572      /**
573 <     * threadFail with message "should throw exception"
573 >     * Calls threadFail with message "should throw exception".
574       */
575      public void threadShouldThrow() {
576 <        threadFailed = true;
293 <        fail("should throw exception");
576 >        threadFail("should throw exception");
577      }
578  
579      /**
580 <     * threadFail with message "should throw" + exceptionName
580 >     * Calls threadFail with message "should throw" + exceptionName.
581       */
582      public void threadShouldThrow(String exceptionName) {
583 <        threadFailed = true;
301 <        fail("should throw " + exceptionName);
583 >        threadFail("should throw " + exceptionName);
584      }
585  
586      /**
587 <     * threadFail with message "Unexpected exception"
587 >     * Records the given exception using {@link #threadRecordFailure},
588 >     * then rethrows the exception, wrapping it in an
589 >     * AssertionFailedError if necessary.
590       */
591 <    public void threadUnexpectedException() {
592 <        threadFailed = true;
593 <        fail("Unexpected exception");
591 >    public void threadUnexpectedException(Throwable t) {
592 >        threadRecordFailure(t);
593 >        t.printStackTrace();
594 >        if (t instanceof RuntimeException)
595 >            throw (RuntimeException) t;
596 >        else if (t instanceof Error)
597 >            throw (Error) t;
598 >        else {
599 >            AssertionFailedError afe =
600 >                new AssertionFailedError("unexpected exception: " + t);
601 >            afe.initCause(t);
602 >            throw afe;
603 >        }
604      }
605  
606      /**
607 <     * threadFail with message "Unexpected exception", with argument
607 >     * Delays, via Thread.sleep, for the given millisecond delay, but
608 >     * if the sleep is shorter than specified, may re-sleep or yield
609 >     * until time elapses.
610       */
611 <    public void threadUnexpectedException(Throwable ex) {
612 <        threadFailed = true;
613 <        ex.printStackTrace();
614 <        fail("Unexpected exception: " + ex);
611 >    static void delay(long millis) throws InterruptedException {
612 >        long startTime = System.nanoTime();
613 >        long ns = millis * 1000 * 1000;
614 >        for (;;) {
615 >            if (millis > 0L)
616 >                Thread.sleep(millis);
617 >            else // too short to sleep
618 >                Thread.yield();
619 >            long d = ns - (System.nanoTime() - startTime);
620 >            if (d > 0L)
621 >                millis = d / (1000 * 1000);
622 >            else
623 >                break;
624 >        }
625      }
626  
627      /**
628 <     * Wait out termination of a thread pool or fail doing so
628 >     * Waits out termination of a thread pool or fails doing so.
629       */
630 <    public void joinPool(ExecutorService exec) {
630 >    void joinPool(ExecutorService exec) {
631          try {
632              exec.shutdown();
633 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
633 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
634 >                fail("ExecutorService " + exec +
635 >                     " did not terminate in a timely manner");
636          } catch (SecurityException ok) {
637              // Allowed in case test doesn't have privs
638          } catch (InterruptedException ie) {
639 <            fail("Unexpected exception");
639 >            fail("Unexpected InterruptedException");
640          }
641      }
642  
643 +    /**
644 +     * A debugging tool to print all stack traces, as jstack does.
645 +     */
646 +    static void printAllStackTraces() {
647 +        for (ThreadInfo info :
648 +                 ManagementFactory.getThreadMXBean()
649 +                 .dumpAllThreads(true, true))
650 +            System.err.print(info);
651 +    }
652  
653      /**
654 <     * fail with message "should throw exception"
654 >     * Checks that thread does not terminate within the default
655 >     * millisecond delay of {@code timeoutMillis()}.
656       */
657 <    public void shouldThrow() {
658 <        fail("Should throw exception");
657 >    void assertThreadStaysAlive(Thread thread) {
658 >        assertThreadStaysAlive(thread, timeoutMillis());
659      }
660  
661      /**
662 <     * fail with message "should throw " + exceptionName
662 >     * Checks that thread does not terminate within the given millisecond delay.
663       */
664 <    public void shouldThrow(String exceptionName) {
665 <        fail("Should throw " + exceptionName);
664 >    void assertThreadStaysAlive(Thread thread, long millis) {
665 >        try {
666 >            // No need to optimize the failing case via Thread.join.
667 >            delay(millis);
668 >            assertTrue(thread.isAlive());
669 >        } catch (InterruptedException ie) {
670 >            fail("Unexpected InterruptedException");
671 >        }
672 >    }
673 >
674 >    /**
675 >     * Checks that the threads do not terminate within the default
676 >     * millisecond delay of {@code timeoutMillis()}.
677 >     */
678 >    void assertThreadsStayAlive(Thread... threads) {
679 >        assertThreadsStayAlive(timeoutMillis(), threads);
680      }
681  
682      /**
683 <     * fail with message "Unexpected exception"
683 >     * Checks that the threads do not terminate within the given millisecond delay.
684       */
685 <    public void unexpectedException() {
686 <        fail("Unexpected exception");
685 >    void assertThreadsStayAlive(long millis, Thread... threads) {
686 >        try {
687 >            // No need to optimize the failing case via Thread.join.
688 >            delay(millis);
689 >            for (Thread thread : threads)
690 >                assertTrue(thread.isAlive());
691 >        } catch (InterruptedException ie) {
692 >            fail("Unexpected InterruptedException");
693 >        }
694 >    }
695 >
696 >    /**
697 >     * Checks that future.get times out, with the default timeout of
698 >     * {@code timeoutMillis()}.
699 >     */
700 >    void assertFutureTimesOut(Future future) {
701 >        assertFutureTimesOut(future, timeoutMillis());
702 >    }
703 >
704 >    /**
705 >     * Checks that future.get times out, with the given millisecond timeout.
706 >     */
707 >    void assertFutureTimesOut(Future future, long timeoutMillis) {
708 >        long startTime = System.nanoTime();
709 >        try {
710 >            future.get(timeoutMillis, MILLISECONDS);
711 >            shouldThrow();
712 >        } catch (TimeoutException success) {
713 >        } catch (Exception e) {
714 >            threadUnexpectedException(e);
715 >        } finally { future.cancel(true); }
716 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
717      }
718  
719      /**
720 <     * fail with message "Unexpected exception", with argument
720 >     * Fails with message "should throw exception".
721       */
722 <    public void unexpectedException(Throwable ex) {
723 <        ex.printStackTrace();
362 <        fail("Unexpected exception: " + ex);
722 >    public void shouldThrow() {
723 >        fail("Should throw exception");
724      }
725  
726 +    /**
727 +     * Fails with message "should throw " + exceptionName.
728 +     */
729 +    public void shouldThrow(String exceptionName) {
730 +        fail("Should throw " + exceptionName);
731 +    }
732  
733      /**
734       * The number of elements to place in collections, arrays, etc.
735       */
736 <    static final int SIZE = 20;
736 >    public static final int SIZE = 20;
737  
738      // Some convenient Integer constants
739  
740 <    static final Integer zero = new Integer(0);
741 <    static final Integer one = new Integer(1);
742 <    static final Integer two = new Integer(2);
743 <    static final Integer three  = new Integer(3);
744 <    static final Integer four  = new Integer(4);
745 <    static final Integer five  = new Integer(5);
746 <    static final Integer six = new Integer(6);
747 <    static final Integer seven = new Integer(7);
748 <    static final Integer eight = new Integer(8);
749 <    static final Integer nine = new Integer(9);
750 <    static final Integer m1  = new Integer(-1);
751 <    static final Integer m2  = new Integer(-2);
752 <    static final Integer m3  = new Integer(-3);
753 <    static final Integer m4 = new Integer(-4);
754 <    static final Integer m5 = new Integer(-5);
755 <    static final Integer m6 = new Integer(-6);
756 <    static final Integer m10 = new Integer(-10);
740 >    public static final Integer zero  = new Integer(0);
741 >    public static final Integer one   = new Integer(1);
742 >    public static final Integer two   = new Integer(2);
743 >    public static final Integer three = new Integer(3);
744 >    public static final Integer four  = new Integer(4);
745 >    public static final Integer five  = new Integer(5);
746 >    public static final Integer six   = new Integer(6);
747 >    public static final Integer seven = new Integer(7);
748 >    public static final Integer eight = new Integer(8);
749 >    public static final Integer nine  = new Integer(9);
750 >    public static final Integer m1  = new Integer(-1);
751 >    public static final Integer m2  = new Integer(-2);
752 >    public static final Integer m3  = new Integer(-3);
753 >    public static final Integer m4  = new Integer(-4);
754 >    public static final Integer m5  = new Integer(-5);
755 >    public static final Integer m6  = new Integer(-6);
756 >    public static final Integer m10 = new Integer(-10);
757 >
758 >    /**
759 >     * Runs Runnable r with a security policy that permits precisely
760 >     * the specified permissions.  If there is no current security
761 >     * manager, the runnable is run twice, both with and without a
762 >     * security manager.  We require that any security manager permit
763 >     * getPolicy/setPolicy.
764 >     */
765 >    public void runWithPermissions(Runnable r, Permission... permissions) {
766 >        SecurityManager sm = System.getSecurityManager();
767 >        if (sm == null) {
768 >            r.run();
769 >        }
770 >        runWithSecurityManagerWithPermissions(r, permissions);
771 >    }
772 >
773 >    /**
774 >     * Runs Runnable r with a security policy that permits precisely
775 >     * the specified permissions.  If there is no current security
776 >     * manager, a temporary one is set for the duration of the
777 >     * Runnable.  We require that any security manager permit
778 >     * getPolicy/setPolicy.
779 >     */
780 >    public void runWithSecurityManagerWithPermissions(Runnable r,
781 >                                                      Permission... permissions) {
782 >        SecurityManager sm = System.getSecurityManager();
783 >        if (sm == null) {
784 >            Policy savedPolicy = Policy.getPolicy();
785 >            try {
786 >                Policy.setPolicy(permissivePolicy());
787 >                System.setSecurityManager(new SecurityManager());
788 >                runWithSecurityManagerWithPermissions(r, permissions);
789 >            } finally {
790 >                System.setSecurityManager(null);
791 >                Policy.setPolicy(savedPolicy);
792 >            }
793 >        } else {
794 >            Policy savedPolicy = Policy.getPolicy();
795 >            AdjustablePolicy policy = new AdjustablePolicy(permissions);
796 >            Policy.setPolicy(policy);
797 >
798 >            try {
799 >                r.run();
800 >            } finally {
801 >                policy.addPermission(new SecurityPermission("setPolicy"));
802 >                Policy.setPolicy(savedPolicy);
803 >            }
804 >        }
805 >    }
806  
807 +    /**
808 +     * Runs a runnable without any permissions.
809 +     */
810 +    public void runWithoutPermissions(Runnable r) {
811 +        runWithPermissions(r);
812 +    }
813  
814      /**
815       * A security policy where new permissions can be dynamically added
816       * or all cleared.
817       */
818 <    static class AdjustablePolicy extends java.security.Policy {
818 >    public static class AdjustablePolicy extends java.security.Policy {
819          Permissions perms = new Permissions();
820 <        AdjustablePolicy() { }
820 >        AdjustablePolicy(Permission... permissions) {
821 >            for (Permission permission : permissions)
822 >                perms.add(permission);
823 >        }
824          void addPermission(Permission perm) { perms.add(perm); }
825          void clearPermissions() { perms = new Permissions(); }
826          public PermissionCollection getPermissions(CodeSource cs) {
# Line 408 | Line 833 | public class JSR166TestCase extends Test
833              return perms.implies(p);
834          }
835          public void refresh() {}
836 +        public String toString() {
837 +            List<Permission> ps = new ArrayList<Permission>();
838 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
839 +                ps.add(e.nextElement());
840 +            return "AdjustablePolicy with permissions " + ps;
841 +        }
842 +    }
843 +
844 +    /**
845 +     * Returns a policy containing all the permissions we ever need.
846 +     */
847 +    public static Policy permissivePolicy() {
848 +        return new AdjustablePolicy
849 +            // Permissions j.u.c. needs directly
850 +            (new RuntimePermission("modifyThread"),
851 +             new RuntimePermission("getClassLoader"),
852 +             new RuntimePermission("setContextClassLoader"),
853 +             // Permissions needed to change permissions!
854 +             new SecurityPermission("getPolicy"),
855 +             new SecurityPermission("setPolicy"),
856 +             new RuntimePermission("setSecurityManager"),
857 +             // Permissions needed by the junit test harness
858 +             new RuntimePermission("accessDeclaredMembers"),
859 +             new PropertyPermission("*", "read"),
860 +             new java.io.FilePermission("<<ALL FILES>>", "read"));
861      }
862  
863      /**
864 <     * Sleep until the timeout has elapsed, or interrupted.
865 <     * Does <em>NOT</em> throw InterruptedException.
864 >     * Sleeps until the given time has elapsed.
865 >     * Throws AssertionFailedError if interrupted.
866       */
867 <    void sleepTillInterrupted(long timeoutMillis) {
867 >    void sleep(long millis) {
868          try {
869 <            Thread.sleep(timeoutMillis);
870 <        } catch (InterruptedException wakeup) {
869 >            delay(millis);
870 >        } catch (InterruptedException ie) {
871 >            AssertionFailedError afe =
872 >                new AssertionFailedError("Unexpected InterruptedException");
873 >            afe.initCause(ie);
874 >            throw afe;
875 >        }
876 >    }
877 >
878 >    /**
879 >     * Spin-waits up to the specified number of milliseconds for the given
880 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
881 >     */
882 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
883 >        long startTime = System.nanoTime();
884 >        for (;;) {
885 >            Thread.State s = thread.getState();
886 >            if (s == Thread.State.BLOCKED ||
887 >                s == Thread.State.WAITING ||
888 >                s == Thread.State.TIMED_WAITING)
889 >                return;
890 >            else if (s == Thread.State.TERMINATED)
891 >                fail("Unexpected thread termination");
892 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
893 >                threadAssertTrue(thread.isAlive());
894 >                return;
895 >            }
896 >            Thread.yield();
897          }
898      }
899  
900      /**
901 <     * Returns a new started Thread running the given runnable.
901 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
902 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
903 >     */
904 >    void waitForThreadToEnterWaitState(Thread thread) {
905 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
906 >    }
907 >
908 >    /**
909 >     * Returns the number of milliseconds since time given by
910 >     * startNanoTime, which must have been previously returned from a
911 >     * call to {@link System.nanoTime()}.
912 >     */
913 >    static long millisElapsedSince(long startNanoTime) {
914 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
915 >    }
916 >
917 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
918 > //         long startTime = System.nanoTime();
919 > //         try {
920 > //             r.run();
921 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
922 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
923 > //             throw new AssertionFailedError("did not return promptly");
924 > //     }
925 >
926 > //     void assertTerminatesPromptly(Runnable r) {
927 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
928 > //     }
929 >
930 >    /**
931 >     * Checks that timed f.get() returns the expected value, and does not
932 >     * wait for the timeout to elapse before returning.
933 >     */
934 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
935 >        long startTime = System.nanoTime();
936 >        try {
937 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
938 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
939 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
940 >            throw new AssertionFailedError("timed get did not return promptly");
941 >    }
942 >
943 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
944 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
945 >    }
946 >
947 >    /**
948 >     * Returns a new started daemon Thread running the given runnable.
949       */
950      Thread newStartedThread(Runnable runnable) {
951          Thread t = new Thread(runnable);
952 +        t.setDaemon(true);
953          t.start();
954          return t;
955      }
956  
957 +    /**
958 +     * Waits for the specified time (in milliseconds) for the thread
959 +     * to terminate (using {@link Thread#join(long)}), else interrupts
960 +     * the thread (in the hope that it may terminate later) and fails.
961 +     */
962 +    void awaitTermination(Thread t, long timeoutMillis) {
963 +        try {
964 +            t.join(timeoutMillis);
965 +        } catch (InterruptedException ie) {
966 +            threadUnexpectedException(ie);
967 +        } finally {
968 +            if (t.getState() != Thread.State.TERMINATED) {
969 +                t.interrupt();
970 +                fail("Test timed out");
971 +            }
972 +        }
973 +    }
974 +
975 +    /**
976 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
977 +     * terminate (using {@link Thread#join(long)}), else interrupts
978 +     * the thread (in the hope that it may terminate later) and fails.
979 +     */
980 +    void awaitTermination(Thread t) {
981 +        awaitTermination(t, LONG_DELAY_MS);
982 +    }
983 +
984      // Some convenient Runnable classes
985  
986 <    abstract class CheckedRunnable implements Runnable {
987 <        abstract void realRun() throws Throwable;
986 >    public abstract class CheckedRunnable implements Runnable {
987 >        protected abstract void realRun() throws Throwable;
988  
989          public final void run() {
990              try {
# Line 444 | Line 995 | public class JSR166TestCase extends Test
995          }
996      }
997  
998 <    abstract class RunnableShouldThrow implements Runnable {
999 <        abstract void realRun() throws Throwable;
998 >    public abstract class RunnableShouldThrow implements Runnable {
999 >        protected abstract void realRun() throws Throwable;
1000  
1001          final Class<?> exceptionClass;
1002  
# Line 457 | Line 1008 | public class JSR166TestCase extends Test
1008              try {
1009                  realRun();
1010                  threadShouldThrow(exceptionClass.getSimpleName());
460            } catch (InterruptedException success) {
1011              } catch (Throwable t) {
1012                  if (! exceptionClass.isInstance(t))
1013                      threadUnexpectedException(t);
# Line 465 | Line 1015 | public class JSR166TestCase extends Test
1015          }
1016      }
1017  
1018 <    abstract class ThreadShouldThrow extends Thread {
1019 <        abstract void realRun() throws Throwable;
1018 >    public abstract class ThreadShouldThrow extends Thread {
1019 >        protected abstract void realRun() throws Throwable;
1020  
1021          final Class<?> exceptionClass;
1022  
# Line 478 | Line 1028 | public class JSR166TestCase extends Test
1028              try {
1029                  realRun();
1030                  threadShouldThrow(exceptionClass.getSimpleName());
481            } catch (InterruptedException success) {
1031              } catch (Throwable t) {
1032                  if (! exceptionClass.isInstance(t))
1033                      threadUnexpectedException(t);
# Line 486 | Line 1035 | public class JSR166TestCase extends Test
1035          }
1036      }
1037  
1038 <    abstract class CheckedInterruptedRunnable implements Runnable {
1039 <        abstract void realRun() throws Throwable;
1038 >    public abstract class CheckedInterruptedRunnable implements Runnable {
1039 >        protected abstract void realRun() throws Throwable;
1040  
1041          public final void run() {
1042              try {
1043                  realRun();
1044                  threadShouldThrow("InterruptedException");
1045              } catch (InterruptedException success) {
1046 +                threadAssertFalse(Thread.interrupted());
1047              } catch (Throwable t) {
1048                  threadUnexpectedException(t);
1049              }
1050          }
1051      }
1052  
1053 <    abstract class CheckedCallable<T> implements Callable<T> {
1054 <        abstract T realCall() throws Throwable;
1053 >    public abstract class CheckedCallable<T> implements Callable<T> {
1054 >        protected abstract T realCall() throws Throwable;
1055  
1056          public final T call() {
1057              try {
1058                  return realCall();
1059              } catch (Throwable t) {
1060                  threadUnexpectedException(t);
1061 +                return null;
1062              }
512            return null;
1063          }
1064      }
1065  
1066 <    abstract class CheckedInterruptedCallable<T> implements Callable<T> {
1067 <        abstract T realCall() throws Throwable;
1066 >    public abstract class CheckedInterruptedCallable<T>
1067 >        implements Callable<T> {
1068 >        protected abstract T realCall() throws Throwable;
1069  
1070          public final T call() {
1071              try {
# Line 522 | Line 1073 | public class JSR166TestCase extends Test
1073                  threadShouldThrow("InterruptedException");
1074                  return result;
1075              } catch (InterruptedException success) {
1076 +                threadAssertFalse(Thread.interrupted());
1077              } catch (Throwable t) {
1078                  threadUnexpectedException(t);
1079              }
# Line 529 | Line 1081 | public class JSR166TestCase extends Test
1081          }
1082      }
1083  
1084 <    static class NoOpRunnable implements Runnable {
1084 >    public static class NoOpRunnable implements Runnable {
1085          public void run() {}
1086      }
1087  
1088 <    static class NoOpCallable implements Callable {
1088 >    public static class NoOpCallable implements Callable {
1089          public Object call() { return Boolean.TRUE; }
1090      }
1091  
1092 <    static final String TEST_STRING = "a test string";
1092 >    public static final String TEST_STRING = "a test string";
1093  
1094 <    static class StringTask implements Callable<String> {
1094 >    public static class StringTask implements Callable<String> {
1095          public String call() { return TEST_STRING; }
1096      }
1097  
1098 <    static class NPETask implements Callable<String> {
1098 >    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1099 >        return new CheckedCallable<String>() {
1100 >            protected String realCall() {
1101 >                try {
1102 >                    latch.await();
1103 >                } catch (InterruptedException quittingTime) {}
1104 >                return TEST_STRING;
1105 >            }};
1106 >    }
1107 >
1108 >    public Runnable awaiter(final CountDownLatch latch) {
1109 >        return new CheckedRunnable() {
1110 >            public void realRun() throws InterruptedException {
1111 >                await(latch);
1112 >            }};
1113 >    }
1114 >
1115 >    public void await(CountDownLatch latch) {
1116 >        try {
1117 >            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1118 >        } catch (Throwable t) {
1119 >            threadUnexpectedException(t);
1120 >        }
1121 >    }
1122 >
1123 >    public void await(Semaphore semaphore) {
1124 >        try {
1125 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1126 >        } catch (Throwable t) {
1127 >            threadUnexpectedException(t);
1128 >        }
1129 >    }
1130 >
1131 > //     /**
1132 > //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1133 > //      */
1134 > //     public void await(AtomicBoolean flag) {
1135 > //         await(flag, LONG_DELAY_MS);
1136 > //     }
1137 >
1138 > //     /**
1139 > //      * Spin-waits up to the specified timeout until flag becomes true.
1140 > //      */
1141 > //     public void await(AtomicBoolean flag, long timeoutMillis) {
1142 > //         long startTime = System.nanoTime();
1143 > //         while (!flag.get()) {
1144 > //             if (millisElapsedSince(startTime) > timeoutMillis)
1145 > //                 throw new AssertionFailedError("timed out");
1146 > //             Thread.yield();
1147 > //         }
1148 > //     }
1149 >
1150 >    public static class NPETask implements Callable<String> {
1151          public String call() { throw new NullPointerException(); }
1152      }
1153  
1154 <    static class CallableOne implements Callable<Integer> {
1154 >    public static class CallableOne implements Callable<Integer> {
1155          public Integer call() { return one; }
1156      }
1157  
1158 <    class ShortRunnable extends CheckedRunnable {
1159 <        void realRun() throws Throwable {
1160 <            Thread.sleep(SHORT_DELAY_MS);
1158 >    public class ShortRunnable extends CheckedRunnable {
1159 >        protected void realRun() throws Throwable {
1160 >            delay(SHORT_DELAY_MS);
1161          }
1162      }
1163  
1164 <    class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1165 <        void realRun() throws InterruptedException {
1166 <            Thread.sleep(SHORT_DELAY_MS);
1164 >    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1165 >        protected void realRun() throws InterruptedException {
1166 >            delay(SHORT_DELAY_MS);
1167          }
1168      }
1169  
1170 <    class SmallRunnable extends CheckedRunnable {
1171 <        void realRun() throws Throwable {
1172 <            Thread.sleep(SMALL_DELAY_MS);
1170 >    public class SmallRunnable extends CheckedRunnable {
1171 >        protected void realRun() throws Throwable {
1172 >            delay(SMALL_DELAY_MS);
1173          }
1174      }
1175  
1176 <    class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1177 <        void realRun() {
1176 >    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1177 >        protected void realRun() {
1178              try {
1179 <                Thread.sleep(SMALL_DELAY_MS);
1180 <            }
577 <            catch (InterruptedException ok) {
578 <            }
1179 >                delay(SMALL_DELAY_MS);
1180 >            } catch (InterruptedException ok) {}
1181          }
1182      }
1183  
1184 <    class SmallCallable extends CheckedCallable {
1185 <        Object realCall() throws Throwable {
1186 <            Thread.sleep(SMALL_DELAY_MS);
1184 >    public class SmallCallable extends CheckedCallable {
1185 >        protected Object realCall() throws InterruptedException {
1186 >            delay(SMALL_DELAY_MS);
1187              return Boolean.TRUE;
1188          }
1189      }
1190  
1191 <    class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
1192 <        void realRun() throws InterruptedException {
1193 <            Thread.sleep(SMALL_DELAY_MS);
1191 >    public class MediumRunnable extends CheckedRunnable {
1192 >        protected void realRun() throws Throwable {
1193 >            delay(MEDIUM_DELAY_MS);
1194          }
1195      }
1196  
1197 <    class MediumRunnable extends CheckedRunnable {
1198 <        void realRun() throws Throwable {
1199 <            Thread.sleep(MEDIUM_DELAY_MS);
1197 >    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1198 >        protected void realRun() throws InterruptedException {
1199 >            delay(MEDIUM_DELAY_MS);
1200          }
1201      }
1202  
1203 <    class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1204 <        void realRun() throws InterruptedException {
1205 <            Thread.sleep(MEDIUM_DELAY_MS);
1206 <        }
1203 >    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1204 >        return new CheckedRunnable() {
1205 >            protected void realRun() {
1206 >                try {
1207 >                    delay(timeoutMillis);
1208 >                } catch (InterruptedException ok) {}
1209 >            }};
1210      }
1211  
1212 <    class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1213 <        void realRun() {
1212 >    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1213 >        protected void realRun() {
1214              try {
1215 <                Thread.sleep(MEDIUM_DELAY_MS);
1216 <            }
612 <            catch (InterruptedException ok) {
613 <            }
1215 >                delay(MEDIUM_DELAY_MS);
1216 >            } catch (InterruptedException ok) {}
1217          }
1218      }
1219  
1220 <    class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1221 <        void realRun() {
1220 >    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1221 >        protected void realRun() {
1222              try {
1223 <                Thread.sleep(LONG_DELAY_MS);
1224 <            }
622 <            catch (InterruptedException ok) {
623 <            }
1223 >                delay(LONG_DELAY_MS);
1224 >            } catch (InterruptedException ok) {}
1225          }
1226      }
1227  
1228      /**
1229       * For use as ThreadFactory in constructors
1230       */
1231 <    static class SimpleThreadFactory implements ThreadFactory {
1231 >    public static class SimpleThreadFactory implements ThreadFactory {
1232          public Thread newThread(Runnable r) {
1233              return new Thread(r);
1234          }
1235      }
1236  
1237 <    static class TrackedShortRunnable implements Runnable {
1238 <        volatile boolean done = false;
1237 >    public interface TrackedRunnable extends Runnable {
1238 >        boolean isDone();
1239 >    }
1240 >
1241 >    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1242 >        return new TrackedRunnable() {
1243 >                private volatile boolean done = false;
1244 >                public boolean isDone() { return done; }
1245 >                public void run() {
1246 >                    try {
1247 >                        delay(timeoutMillis);
1248 >                        done = true;
1249 >                    } catch (InterruptedException ok) {}
1250 >                }
1251 >            };
1252 >    }
1253 >
1254 >    public static class TrackedShortRunnable implements Runnable {
1255 >        public volatile boolean done = false;
1256          public void run() {
1257              try {
1258 <                Thread.sleep(SMALL_DELAY_MS);
1258 >                delay(SHORT_DELAY_MS);
1259                  done = true;
1260 <            } catch (InterruptedException ok) {
643 <            }
1260 >            } catch (InterruptedException ok) {}
1261          }
1262      }
1263  
1264 <    static class TrackedMediumRunnable implements Runnable {
1265 <        volatile boolean done = false;
1264 >    public static class TrackedSmallRunnable implements Runnable {
1265 >        public volatile boolean done = false;
1266          public void run() {
1267              try {
1268 <                Thread.sleep(MEDIUM_DELAY_MS);
1268 >                delay(SMALL_DELAY_MS);
1269                  done = true;
1270 <            } catch (InterruptedException ok) {
654 <            }
1270 >            } catch (InterruptedException ok) {}
1271          }
1272      }
1273  
1274 <    static class TrackedLongRunnable implements Runnable {
1275 <        volatile boolean done = false;
1274 >    public static class TrackedMediumRunnable implements Runnable {
1275 >        public volatile boolean done = false;
1276          public void run() {
1277              try {
1278 <                Thread.sleep(LONG_DELAY_MS);
1278 >                delay(MEDIUM_DELAY_MS);
1279                  done = true;
1280 <            } catch (InterruptedException ok) {
1281 <            }
1280 >            } catch (InterruptedException ok) {}
1281 >        }
1282 >    }
1283 >
1284 >    public static class TrackedLongRunnable implements Runnable {
1285 >        public volatile boolean done = false;
1286 >        public void run() {
1287 >            try {
1288 >                delay(LONG_DELAY_MS);
1289 >                done = true;
1290 >            } catch (InterruptedException ok) {}
1291          }
1292      }
1293  
1294 <    static class TrackedNoOpRunnable implements Runnable {
1295 <        volatile boolean done = false;
1294 >    public static class TrackedNoOpRunnable implements Runnable {
1295 >        public volatile boolean done = false;
1296          public void run() {
1297              done = true;
1298          }
1299      }
1300  
1301 <    static class TrackedCallable implements Callable {
1302 <        volatile boolean done = false;
1301 >    public static class TrackedCallable implements Callable {
1302 >        public volatile boolean done = false;
1303          public Object call() {
1304              try {
1305 <                Thread.sleep(SMALL_DELAY_MS);
1305 >                delay(SMALL_DELAY_MS);
1306                  done = true;
1307 <            } catch (InterruptedException ok) {
683 <            }
1307 >            } catch (InterruptedException ok) {}
1308              return Boolean.TRUE;
1309          }
1310      }
1311  
1312 +    /**
1313 +     * Analog of CheckedRunnable for RecursiveAction
1314 +     */
1315 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1316 +        protected abstract void realCompute() throws Throwable;
1317 +
1318 +        @Override protected final void compute() {
1319 +            try {
1320 +                realCompute();
1321 +            } catch (Throwable t) {
1322 +                threadUnexpectedException(t);
1323 +            }
1324 +        }
1325 +    }
1326 +
1327 +    /**
1328 +     * Analog of CheckedCallable for RecursiveTask
1329 +     */
1330 +    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1331 +        protected abstract T realCompute() throws Throwable;
1332 +
1333 +        @Override protected final T compute() {
1334 +            try {
1335 +                return realCompute();
1336 +            } catch (Throwable t) {
1337 +                threadUnexpectedException(t);
1338 +                return null;
1339 +            }
1340 +        }
1341 +    }
1342  
1343      /**
1344       * For use as RejectedExecutionHandler in constructors
1345       */
1346 <    static class NoOpREHandler implements RejectedExecutionHandler {
1346 >    public static class NoOpREHandler implements RejectedExecutionHandler {
1347          public void rejectedExecution(Runnable r,
1348                                        ThreadPoolExecutor executor) {}
1349      }
1350  
1351 +    /**
1352 +     * A CyclicBarrier that uses timed await and fails with
1353 +     * AssertionFailedErrors instead of throwing checked exceptions.
1354 +     */
1355 +    public class CheckedBarrier extends CyclicBarrier {
1356 +        public CheckedBarrier(int parties) { super(parties); }
1357 +
1358 +        public int await() {
1359 +            try {
1360 +                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1361 +            } catch (TimeoutException e) {
1362 +                throw new AssertionFailedError("timed out");
1363 +            } catch (Exception e) {
1364 +                AssertionFailedError afe =
1365 +                    new AssertionFailedError("Unexpected exception: " + e);
1366 +                afe.initCause(e);
1367 +                throw afe;
1368 +            }
1369 +        }
1370 +    }
1371 +
1372 +    void checkEmpty(BlockingQueue q) {
1373 +        try {
1374 +            assertTrue(q.isEmpty());
1375 +            assertEquals(0, q.size());
1376 +            assertNull(q.peek());
1377 +            assertNull(q.poll());
1378 +            assertNull(q.poll(0, MILLISECONDS));
1379 +            assertEquals(q.toString(), "[]");
1380 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1381 +            assertFalse(q.iterator().hasNext());
1382 +            try {
1383 +                q.element();
1384 +                shouldThrow();
1385 +            } catch (NoSuchElementException success) {}
1386 +            try {
1387 +                q.iterator().next();
1388 +                shouldThrow();
1389 +            } catch (NoSuchElementException success) {}
1390 +            try {
1391 +                q.remove();
1392 +                shouldThrow();
1393 +            } catch (NoSuchElementException success) {}
1394 +        } catch (InterruptedException ie) {
1395 +            threadUnexpectedException(ie);
1396 +        }
1397 +    }
1398 +
1399 +    void assertSerialEquals(Object x, Object y) {
1400 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1401 +    }
1402 +
1403 +    void assertNotSerialEquals(Object x, Object y) {
1404 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1405 +    }
1406 +
1407 +    byte[] serialBytes(Object o) {
1408 +        try {
1409 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1410 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1411 +            oos.writeObject(o);
1412 +            oos.flush();
1413 +            oos.close();
1414 +            return bos.toByteArray();
1415 +        } catch (Throwable t) {
1416 +            threadUnexpectedException(t);
1417 +            return new byte[0];
1418 +        }
1419 +    }
1420 +
1421 +    @SuppressWarnings("unchecked")
1422 +    <T> T serialClone(T o) {
1423 +        try {
1424 +            ObjectInputStream ois = new ObjectInputStream
1425 +                (new ByteArrayInputStream(serialBytes(o)));
1426 +            T clone = (T) ois.readObject();
1427 +            assertSame(o.getClass(), clone.getClass());
1428 +            return clone;
1429 +        } catch (Throwable t) {
1430 +            threadUnexpectedException(t);
1431 +            return null;
1432 +        }
1433 +    }
1434 +
1435 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1436 +                             Runnable... throwingActions) {
1437 +        for (Runnable throwingAction : throwingActions) {
1438 +            boolean threw = false;
1439 +            try { throwingAction.run(); }
1440 +            catch (Throwable t) {
1441 +                threw = true;
1442 +                if (!expectedExceptionClass.isInstance(t)) {
1443 +                    AssertionFailedError afe =
1444 +                        new AssertionFailedError
1445 +                        ("Expected " + expectedExceptionClass.getName() +
1446 +                         ", got " + t.getClass().getName());
1447 +                    afe.initCause(t);
1448 +                    threadUnexpectedException(afe);
1449 +                }
1450 +            }
1451 +            if (!threw)
1452 +                shouldThrow(expectedExceptionClass.getName());
1453 +        }
1454 +    }
1455   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines