ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.119
Committed: Mon Jun 16 20:13:54 2014 UTC (9 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.118: +4 -0 lines
Log Message:
add javadoc for testImplementationDetails

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