ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.118
Committed: Mon Jun 16 18:01:38 2014 UTC (9 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.117: +3 -0 lines
Log Message:
add simple infrastructure for implementation-dependent tests

File Contents

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