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.4 by dl, Thu Sep 25 11:02:41 2003 UTC vs.
Revision 1.112 by jsr166, Fri Aug 16 07:07:01 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines