ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.61
Committed: Mon Oct 11 03:54:10 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.60: +60 -0 lines
Log Message:
add test profiling support.  Fix TrackedShortRunnable timeout

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     * http://creativecommons.org/licenses/publicdomain
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.53 import java.util.PropertyPermission;
11 dl 1.1 import java.util.concurrent.*;
12 jsr166 1.53 import java.util.concurrent.atomic.AtomicReference;
13 jsr166 1.36 import static java.util.concurrent.TimeUnit.MILLISECONDS;
14 jsr166 1.53 import java.security.CodeSource;
15     import java.security.Permission;
16     import java.security.PermissionCollection;
17     import java.security.Permissions;
18     import java.security.Policy;
19     import java.security.ProtectionDomain;
20     import java.security.SecurityPermission;
21 dl 1.1
22     /**
23 dl 1.5 * Base class for JSR166 Junit TCK tests. Defines some constants,
24     * utility methods and classes, as well as a simple framework for
25     * helping to make sure that assertions failing in generated threads
26     * cause the associated test that generated them to itself fail (which
27 jsr166 1.27 * JUnit does not otherwise arrange). The rules for creating such
28 dl 1.5 * tests are:
29 dl 1.1 *
30     * <ol>
31     *
32     * <li> All assertions in code running in generated threads must use
33 jsr166 1.27 * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
34 dl 1.18 * #threadAssertEquals}, or {@link #threadAssertNull}, (not
35 jsr166 1.50 * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
36 dl 1.1 * particularly recommended) for other code to use these forms too.
37     * Only the most typically used JUnit assertion methods are defined
38     * this way, but enough to live with.</li>
39     *
40 dl 1.18 * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
41 jsr166 1.50 * to invoke {@code super.setUp} and {@code super.tearDown} within
42 dl 1.1 * them. These methods are used to clear and check for thread
43     * assertion failures.</li>
44     *
45 jsr166 1.51 * <li>All delays and timeouts must use one of the constants {@code
46 jsr166 1.50 * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
47     * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
48 dl 1.5 * discriminable from zero time, and always allows enough time for the
49     * small amounts of computation (creating a thread, calling a few
50 dl 1.1 * methods, etc) needed to reach a timeout point. Similarly, a SMALL
51     * is always discriminable as larger than SHORT and smaller than
52     * MEDIUM. And so on. These constants are set to conservative values,
53 dl 1.2 * but even so, if there is ever any doubt, they can all be increased
54 jsr166 1.27 * in one spot to rerun tests on slower platforms.</li>
55 dl 1.1 *
56     * <li> All threads generated must be joined inside each test case
57 jsr166 1.50 * method (or {@code fail} to do so) before returning from the
58     * method. The {@code joinPool} method can be used to do this when
59 dl 1.1 * using Executors.</li>
60     *
61     * </ol>
62 dl 1.6 *
63     * <p> <b>Other notes</b>
64     * <ul>
65     *
66     * <li> Usually, there is one testcase method per JSR166 method
67     * covering "normal" operation, and then as many exception-testing
68     * methods as there are exceptions the method can throw. Sometimes
69     * there are multiple tests per JSR166 method when the different
70     * "normal" behaviors differ significantly. And sometimes testcases
71     * cover multiple methods when they cannot be tested in
72     * isolation.</li>
73 jsr166 1.27 *
74 dl 1.6 * <li> The documentation style for testcases is to provide as javadoc
75     * a simple sentence or two describing the property that the testcase
76     * method purports to test. The javadocs do not say anything about how
77     * the property is tested. To find out, read the code.</li>
78     *
79     * <li> These tests are "conformance tests", and do not attempt to
80     * test throughput, latency, scalability or other performance factors
81     * (see the separate "jtreg" tests for a set intended to check these
82     * for the most central aspects of functionality.) So, most tests use
83     * the smallest sensible numbers of threads, collection sizes, etc
84     * needed to check basic conformance.</li>
85     *
86     * <li>The test classes currently do not declare inclusion in
87     * any particular package to simplify things for people integrating
88     * them in TCK test suites.</li>
89     *
90 jsr166 1.50 * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
91 dl 1.6 * runs all JSR166 unit tests.</li>
92     *
93     * </ul>
94 dl 1.1 */
95     public class JSR166TestCase extends TestCase {
96 jsr166 1.49 private static final boolean useSecurityManager =
97     Boolean.getBoolean("jsr166.useSecurityManager");
98    
99 dl 1.6 /**
100 jsr166 1.61 * If true, report on stdout all "slow" tests, that is, ones that
101     * take more than profileThreshold milliseconds to execute.
102     */
103     private static final boolean profileTests =
104     Boolean.getBoolean("jsr166.profileTests");
105    
106     /**
107     * The number of milliseconds that tests are permitted for
108     * execution without being reported, when profileTests is set.
109     */
110     private static final long profileThreshold =
111     Long.getLong("jsr166.profileThreshold", 100);
112    
113     protected void runTest() throws Throwable {
114     if (profileTests)
115     runTestProfiled();
116     else
117     super.runTest();
118     }
119    
120     protected void runTestProfiled() throws Throwable {
121     long t0 = System.nanoTime();
122     try {
123     super.runTest();
124     } finally {
125     long elapsedMillis =
126     (System.nanoTime() - t0) / (1000L * 1000L);
127     if (elapsedMillis >= profileThreshold)
128     System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
129     }
130     }
131    
132     /**
133 dl 1.6 * Runs all JSR166 unit tests using junit.textui.TestRunner
134 jsr166 1.27 */
135 jsr166 1.41 public static void main(String[] args) {
136 jsr166 1.49 if (useSecurityManager) {
137     System.err.println("Setting a permissive security manager");
138     Policy.setPolicy(permissivePolicy());
139     System.setSecurityManager(new SecurityManager());
140     }
141 jsr166 1.56 int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
142    
143 dl 1.16 Test s = suite();
144 dl 1.22 for (int i = 0; i < iters; ++i) {
145 jsr166 1.41 junit.textui.TestRunner.run(s);
146 dl 1.22 System.gc();
147     System.runFinalization();
148     }
149     System.exit(0);
150 dl 1.6 }
151    
152 jsr166 1.60 public static TestSuite newTestSuite(Object... suiteOrClasses) {
153     TestSuite suite = new TestSuite();
154     for (Object suiteOrClass : suiteOrClasses) {
155     if (suiteOrClass instanceof TestSuite)
156     suite.addTest((TestSuite) suiteOrClass);
157     else if (suiteOrClass instanceof Class)
158     suite.addTest(new TestSuite((Class<?>) suiteOrClass));
159     else
160     throw new ClassCastException("not a test suite or class");
161     }
162     return suite;
163     }
164    
165 dl 1.6 /**
166 jsr166 1.60 * Collects all JSR166 unit tests as one suite.
167 jsr166 1.27 */
168 jsr166 1.41 public static Test suite() {
169 jsr166 1.60 return newTestSuite(
170     ForkJoinPoolTest.suite(),
171     ForkJoinTaskTest.suite(),
172     RecursiveActionTest.suite(),
173     RecursiveTaskTest.suite(),
174     LinkedTransferQueueTest.suite(),
175     PhaserTest.suite(),
176     ThreadLocalRandomTest.suite(),
177     AbstractExecutorServiceTest.suite(),
178     AbstractQueueTest.suite(),
179     AbstractQueuedSynchronizerTest.suite(),
180     AbstractQueuedLongSynchronizerTest.suite(),
181     ArrayBlockingQueueTest.suite(),
182     ArrayDequeTest.suite(),
183     AtomicBooleanTest.suite(),
184     AtomicIntegerArrayTest.suite(),
185     AtomicIntegerFieldUpdaterTest.suite(),
186     AtomicIntegerTest.suite(),
187     AtomicLongArrayTest.suite(),
188     AtomicLongFieldUpdaterTest.suite(),
189     AtomicLongTest.suite(),
190     AtomicMarkableReferenceTest.suite(),
191     AtomicReferenceArrayTest.suite(),
192     AtomicReferenceFieldUpdaterTest.suite(),
193     AtomicReferenceTest.suite(),
194     AtomicStampedReferenceTest.suite(),
195     ConcurrentHashMapTest.suite(),
196     ConcurrentLinkedDequeTest.suite(),
197     ConcurrentLinkedQueueTest.suite(),
198     ConcurrentSkipListMapTest.suite(),
199     ConcurrentSkipListSubMapTest.suite(),
200     ConcurrentSkipListSetTest.suite(),
201     ConcurrentSkipListSubSetTest.suite(),
202     CopyOnWriteArrayListTest.suite(),
203     CopyOnWriteArraySetTest.suite(),
204     CountDownLatchTest.suite(),
205     CyclicBarrierTest.suite(),
206     DelayQueueTest.suite(),
207     EntryTest.suite(),
208     ExchangerTest.suite(),
209     ExecutorsTest.suite(),
210     ExecutorCompletionServiceTest.suite(),
211     FutureTaskTest.suite(),
212     LinkedBlockingDequeTest.suite(),
213     LinkedBlockingQueueTest.suite(),
214     LinkedListTest.suite(),
215     LockSupportTest.suite(),
216     PriorityBlockingQueueTest.suite(),
217     PriorityQueueTest.suite(),
218     ReentrantLockTest.suite(),
219     ReentrantReadWriteLockTest.suite(),
220     ScheduledExecutorTest.suite(),
221     ScheduledExecutorSubclassTest.suite(),
222     SemaphoreTest.suite(),
223     SynchronousQueueTest.suite(),
224     SystemTest.suite(),
225     ThreadLocalTest.suite(),
226     ThreadPoolExecutorTest.suite(),
227     ThreadPoolExecutorSubclassTest.suite(),
228     ThreadTest.suite(),
229     TimeUnitTest.suite(),
230     TreeMapTest.suite(),
231     TreeSetTest.suite(),
232     TreeSubMapTest.suite(),
233     TreeSubSetTest.suite());
234 dl 1.6 }
235    
236 dl 1.1
237 dl 1.2 public static long SHORT_DELAY_MS;
238     public static long SMALL_DELAY_MS;
239     public static long MEDIUM_DELAY_MS;
240     public static long LONG_DELAY_MS;
241    
242    
243     /**
244 jsr166 1.27 * Returns the shortest timed delay. This could
245 dl 1.15 * be reimplemented to use for example a Property.
246 jsr166 1.27 */
247 dl 1.2 protected long getShortDelay() {
248 dl 1.21 return 50;
249 dl 1.2 }
250    
251    
252     /**
253 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
254 dl 1.2 */
255 jsr166 1.43 protected void setDelays() {
256 dl 1.2 SHORT_DELAY_MS = getShortDelay();
257 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
258 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
259 jsr166 1.53 LONG_DELAY_MS = SHORT_DELAY_MS * 50;
260 dl 1.2 }
261    
262 dl 1.1 /**
263 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
264 dl 1.1 */
265 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
266     = new AtomicReference<Throwable>(null);
267 dl 1.1
268     /**
269 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
270     * harness thread, triggering a test case failure. Only the first
271     * failure is recorded; subsequent calls to this method from within
272     * the same test have no effect.
273 dl 1.1 */
274 jsr166 1.53 public void threadRecordFailure(Throwable t) {
275     threadFailure.compareAndSet(null, t);
276     }
277    
278 jsr166 1.27 public void setUp() {
279 dl 1.2 setDelays();
280 dl 1.1 }
281    
282     /**
283 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
284     * by rethrowing, in the test harness thread, any exception recorded
285     * earlier by threadRecordFailure.
286     */
287     public void tearDown() throws Exception {
288     Throwable t = threadFailure.get();
289     if (t != null) {
290     if (t instanceof Error)
291     throw (Error) t;
292     else if (t instanceof RuntimeException)
293     throw (RuntimeException) t;
294     else if (t instanceof Exception)
295     throw (Exception) t;
296 jsr166 1.57 else {
297     AssertionFailedError afe =
298     new AssertionFailedError(t.toString());
299     afe.initCause(t);
300     throw afe;
301     }
302 jsr166 1.53 }
303 dl 1.1 }
304    
305 dl 1.5 /**
306 jsr166 1.53 * Just like fail(reason), but additionally recording (using
307 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
308     * the current testcase will fail.
309 jsr166 1.27 */
310 dl 1.1 public void threadFail(String reason) {
311 jsr166 1.53 try {
312     fail(reason);
313 jsr166 1.57 } catch (AssertionFailedError t) {
314 jsr166 1.53 threadRecordFailure(t);
315     fail(reason);
316     }
317 dl 1.1 }
318    
319 dl 1.5 /**
320 jsr166 1.53 * Just like assertTrue(b), but additionally recording (using
321 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
322     * the current testcase will fail.
323 jsr166 1.27 */
324 dl 1.1 public void threadAssertTrue(boolean b) {
325 jsr166 1.53 try {
326 dl 1.1 assertTrue(b);
327 jsr166 1.57 } catch (AssertionFailedError t) {
328 jsr166 1.53 threadRecordFailure(t);
329     throw t;
330 dl 1.1 }
331     }
332 dl 1.5
333     /**
334 jsr166 1.53 * Just like assertFalse(b), but additionally recording (using
335 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
336     * the current testcase will fail.
337 jsr166 1.27 */
338 dl 1.1 public void threadAssertFalse(boolean b) {
339 jsr166 1.53 try {
340 dl 1.1 assertFalse(b);
341 jsr166 1.57 } catch (AssertionFailedError t) {
342 jsr166 1.53 threadRecordFailure(t);
343     throw t;
344 dl 1.1 }
345     }
346 dl 1.5
347     /**
348 jsr166 1.53 * Just like assertNull(x), but additionally recording (using
349 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
350     * the current testcase will fail.
351 jsr166 1.27 */
352 dl 1.1 public void threadAssertNull(Object x) {
353 jsr166 1.53 try {
354 dl 1.1 assertNull(x);
355 jsr166 1.57 } catch (AssertionFailedError t) {
356 jsr166 1.53 threadRecordFailure(t);
357     throw t;
358 dl 1.1 }
359     }
360 dl 1.5
361     /**
362 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
363 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
364     * the current testcase will fail.
365 jsr166 1.27 */
366 dl 1.1 public void threadAssertEquals(long x, long y) {
367 jsr166 1.53 try {
368 dl 1.1 assertEquals(x, y);
369 jsr166 1.57 } catch (AssertionFailedError t) {
370 jsr166 1.53 threadRecordFailure(t);
371     throw t;
372 dl 1.1 }
373     }
374 dl 1.5
375     /**
376 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
377 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
378     * the current testcase will fail.
379 jsr166 1.27 */
380 dl 1.1 public void threadAssertEquals(Object x, Object y) {
381 jsr166 1.53 try {
382 dl 1.1 assertEquals(x, y);
383 jsr166 1.57 } catch (AssertionFailedError t) {
384 jsr166 1.53 threadRecordFailure(t);
385     throw t;
386 jsr166 1.57 } catch (Throwable t) {
387     threadUnexpectedException(t);
388 dl 1.1 }
389     }
390    
391 dl 1.5 /**
392 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
393 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
394     * the current testcase will fail.
395 jsr166 1.52 */
396     public void threadAssertSame(Object x, Object y) {
397 jsr166 1.53 try {
398 jsr166 1.52 assertSame(x, y);
399 jsr166 1.57 } catch (AssertionFailedError t) {
400 jsr166 1.53 threadRecordFailure(t);
401     throw t;
402 jsr166 1.52 }
403     }
404    
405     /**
406 jsr166 1.53 * Calls threadFail with message "should throw exception".
407 jsr166 1.33 */
408 dl 1.3 public void threadShouldThrow() {
409 jsr166 1.53 threadFail("should throw exception");
410 dl 1.3 }
411    
412 dl 1.5 /**
413 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
414 jsr166 1.40 */
415     public void threadShouldThrow(String exceptionName) {
416 jsr166 1.53 threadFail("should throw " + exceptionName);
417 dl 1.3 }
418    
419 dl 1.31 /**
420 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
421     * then rethrows the exception, wrapping it in an
422     * AssertionFailedError if necessary.
423 dl 1.31 */
424 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
425     threadRecordFailure(t);
426     t.printStackTrace();
427     if (t instanceof RuntimeException)
428     throw (RuntimeException) t;
429     else if (t instanceof Error)
430     throw (Error) t;
431     else {
432 jsr166 1.57 AssertionFailedError afe =
433     new AssertionFailedError("unexpected exception: " + t);
434 jsr166 1.53 t.initCause(t);
435 jsr166 1.57 throw afe;
436 jsr166 1.55 }
437 dl 1.31 }
438 dl 1.3
439 dl 1.1 /**
440 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
441 dl 1.1 */
442     public void joinPool(ExecutorService exec) {
443     try {
444     exec.shutdown();
445 jsr166 1.54 assertTrue("ExecutorService did not terminate in a timely manner",
446     exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
447 jsr166 1.33 } catch (SecurityException ok) {
448 dl 1.22 // Allowed in case test doesn't have privs
449 jsr166 1.33 } catch (InterruptedException ie) {
450 jsr166 1.44 fail("Unexpected InterruptedException");
451 dl 1.1 }
452     }
453    
454 dl 1.5
455     /**
456 jsr166 1.53 * Fails with message "should throw exception".
457 jsr166 1.27 */
458 dl 1.3 public void shouldThrow() {
459     fail("Should throw exception");
460     }
461    
462 dl 1.5 /**
463 jsr166 1.53 * Fails with message "should throw " + exceptionName.
464 jsr166 1.40 */
465     public void shouldThrow(String exceptionName) {
466     fail("Should throw " + exceptionName);
467     }
468    
469     /**
470 dl 1.1 * The number of elements to place in collections, arrays, etc.
471     */
472 jsr166 1.45 public static final int SIZE = 20;
473 dl 1.1
474     // Some convenient Integer constants
475    
476 jsr166 1.47 public static final Integer zero = new Integer(0);
477     public static final Integer one = new Integer(1);
478     public static final Integer two = new Integer(2);
479     public static final Integer three = new Integer(3);
480 jsr166 1.45 public static final Integer four = new Integer(4);
481     public static final Integer five = new Integer(5);
482 jsr166 1.47 public static final Integer six = new Integer(6);
483 jsr166 1.45 public static final Integer seven = new Integer(7);
484     public static final Integer eight = new Integer(8);
485 jsr166 1.47 public static final Integer nine = new Integer(9);
486 jsr166 1.45 public static final Integer m1 = new Integer(-1);
487     public static final Integer m2 = new Integer(-2);
488     public static final Integer m3 = new Integer(-3);
489 jsr166 1.47 public static final Integer m4 = new Integer(-4);
490     public static final Integer m5 = new Integer(-5);
491     public static final Integer m6 = new Integer(-6);
492 jsr166 1.45 public static final Integer m10 = new Integer(-10);
493 dl 1.7
494    
495     /**
496 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
497     * the specified permissions. If there is no current security
498     * manager, the runnable is run twice, both with and without a
499     * security manager. We require that any security manager permit
500     * getPolicy/setPolicy.
501     */
502     public void runWithPermissions(Runnable r, Permission... permissions) {
503     SecurityManager sm = System.getSecurityManager();
504     if (sm == null) {
505     r.run();
506     Policy savedPolicy = Policy.getPolicy();
507     try {
508     Policy.setPolicy(permissivePolicy());
509     System.setSecurityManager(new SecurityManager());
510     runWithPermissions(r, permissions);
511     } finally {
512     System.setSecurityManager(null);
513     Policy.setPolicy(savedPolicy);
514     }
515     } else {
516     Policy savedPolicy = Policy.getPolicy();
517     AdjustablePolicy policy = new AdjustablePolicy(permissions);
518     Policy.setPolicy(policy);
519    
520     try {
521     r.run();
522     } finally {
523     policy.addPermission(new SecurityPermission("setPolicy"));
524     Policy.setPolicy(savedPolicy);
525     }
526     }
527     }
528    
529     /**
530     * Runs a runnable without any permissions.
531     */
532     public void runWithoutPermissions(Runnable r) {
533     runWithPermissions(r);
534     }
535    
536     /**
537 dl 1.7 * A security policy where new permissions can be dynamically added
538     * or all cleared.
539     */
540 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
541 dl 1.7 Permissions perms = new Permissions();
542 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
543     for (Permission permission : permissions)
544     perms.add(permission);
545     }
546 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
547     void clearPermissions() { perms = new Permissions(); }
548 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
549     return perms;
550     }
551     public PermissionCollection getPermissions(ProtectionDomain pd) {
552     return perms;
553     }
554     public boolean implies(ProtectionDomain pd, Permission p) {
555     return perms.implies(p);
556     }
557     public void refresh() {}
558 dl 1.7 }
559 dl 1.1
560 jsr166 1.38 /**
561 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
562     */
563     public static Policy permissivePolicy() {
564     return new AdjustablePolicy
565     // Permissions j.u.c. needs directly
566     (new RuntimePermission("modifyThread"),
567     new RuntimePermission("getClassLoader"),
568     new RuntimePermission("setContextClassLoader"),
569     // Permissions needed to change permissions!
570     new SecurityPermission("getPolicy"),
571     new SecurityPermission("setPolicy"),
572     new RuntimePermission("setSecurityManager"),
573     // Permissions needed by the junit test harness
574     new RuntimePermission("accessDeclaredMembers"),
575     new PropertyPermission("*", "read"),
576     new java.io.FilePermission("<<ALL FILES>>", "read"));
577     }
578    
579     /**
580 jsr166 1.60 * Sleeps until the given time has elapsed.
581     * Throws AssertionFailedError if interrupted.
582     */
583     void sleep(long millis) {
584     try {
585     Thread.sleep(millis);
586     } catch (InterruptedException ie) {
587     AssertionFailedError afe =
588     new AssertionFailedError("Unexpected InterruptedException");
589     afe.initCause(ie);
590     throw afe;
591     }
592     }
593    
594     /**
595 jsr166 1.59 * Sleeps until the timeout has elapsed, or interrupted.
596 jsr166 1.38 * Does <em>NOT</em> throw InterruptedException.
597     */
598     void sleepTillInterrupted(long timeoutMillis) {
599     try {
600     Thread.sleep(timeoutMillis);
601 jsr166 1.44 } catch (InterruptedException wakeup) {}
602 jsr166 1.38 }
603    
604     /**
605 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
606 jsr166 1.38 */
607     Thread newStartedThread(Runnable runnable) {
608     Thread t = new Thread(runnable);
609 jsr166 1.58 t.setDaemon(true);
610 jsr166 1.38 t.start();
611     return t;
612     }
613 dl 1.1
614 jsr166 1.59 /**
615     * Waits for the specified time (in milliseconds) for the thread
616     * to terminate (using {@link Thread#join(long)}), else interrupts
617     * the thread (in the hope that it may terminate later) and fails.
618     */
619     void awaitTermination(Thread t, long timeoutMillis) {
620     try {
621     t.join(timeoutMillis);
622     } catch (InterruptedException ie) {
623     threadUnexpectedException(ie);
624     } finally {
625     if (t.isAlive()) {
626     t.interrupt();
627     fail("Test timed out");
628     }
629     }
630     }
631    
632 dl 1.1 // Some convenient Runnable classes
633    
634 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
635     protected abstract void realRun() throws Throwable;
636 jsr166 1.35
637     public final void run() {
638     try {
639     realRun();
640     } catch (Throwable t) {
641     threadUnexpectedException(t);
642     }
643     }
644     }
645    
646 jsr166 1.45 public abstract class RunnableShouldThrow implements Runnable {
647     protected abstract void realRun() throws Throwable;
648 jsr166 1.40
649     final Class<?> exceptionClass;
650    
651     <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
652     this.exceptionClass = exceptionClass;
653     }
654    
655     public final void run() {
656     try {
657     realRun();
658     threadShouldThrow(exceptionClass.getSimpleName());
659     } catch (Throwable t) {
660     if (! exceptionClass.isInstance(t))
661     threadUnexpectedException(t);
662     }
663     }
664     }
665    
666 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
667     protected abstract void realRun() throws Throwable;
668 jsr166 1.40
669     final Class<?> exceptionClass;
670    
671     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
672     this.exceptionClass = exceptionClass;
673     }
674    
675     public final void run() {
676     try {
677     realRun();
678     threadShouldThrow(exceptionClass.getSimpleName());
679     } catch (Throwable t) {
680     if (! exceptionClass.isInstance(t))
681     threadUnexpectedException(t);
682     }
683     }
684     }
685    
686 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
687     protected abstract void realRun() throws Throwable;
688 jsr166 1.35
689     public final void run() {
690     try {
691     realRun();
692 jsr166 1.40 threadShouldThrow("InterruptedException");
693 jsr166 1.35 } catch (InterruptedException success) {
694     } catch (Throwable t) {
695     threadUnexpectedException(t);
696     }
697     }
698     }
699    
700 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
701     protected abstract T realCall() throws Throwable;
702 jsr166 1.35
703     public final T call() {
704     try {
705     return realCall();
706     } catch (Throwable t) {
707     threadUnexpectedException(t);
708 jsr166 1.53 return null;
709 jsr166 1.35 }
710 jsr166 1.40 }
711     }
712    
713 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
714     implements Callable<T> {
715 jsr166 1.45 protected abstract T realCall() throws Throwable;
716 jsr166 1.40
717     public final T call() {
718     try {
719     T result = realCall();
720     threadShouldThrow("InterruptedException");
721     return result;
722     } catch (InterruptedException success) {
723     } catch (Throwable t) {
724     threadUnexpectedException(t);
725     }
726     return null;
727 jsr166 1.35 }
728     }
729    
730 jsr166 1.45 public static class NoOpRunnable implements Runnable {
731 dl 1.1 public void run() {}
732     }
733    
734 jsr166 1.45 public static class NoOpCallable implements Callable {
735 dl 1.1 public Object call() { return Boolean.TRUE; }
736 dl 1.10 }
737    
738 jsr166 1.45 public static final String TEST_STRING = "a test string";
739 dl 1.10
740 jsr166 1.45 public static class StringTask implements Callable<String> {
741 dl 1.10 public String call() { return TEST_STRING; }
742     }
743    
744 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
745     return new CheckedCallable<String>() {
746     public String realCall() {
747     try {
748     latch.await();
749     } catch (InterruptedException quittingTime) {}
750     return TEST_STRING;
751     }};
752     }
753    
754 jsr166 1.45 public static class NPETask implements Callable<String> {
755 dl 1.10 public String call() { throw new NullPointerException(); }
756     }
757    
758 jsr166 1.45 public static class CallableOne implements Callable<Integer> {
759 dl 1.10 public Integer call() { return one; }
760 dl 1.1 }
761    
762 jsr166 1.45 public class ShortRunnable extends CheckedRunnable {
763     protected void realRun() throws Throwable {
764 jsr166 1.35 Thread.sleep(SHORT_DELAY_MS);
765 dl 1.1 }
766     }
767    
768 jsr166 1.45 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
769     protected void realRun() throws InterruptedException {
770 jsr166 1.35 Thread.sleep(SHORT_DELAY_MS);
771 dl 1.1 }
772     }
773    
774 jsr166 1.45 public class SmallRunnable extends CheckedRunnable {
775     protected void realRun() throws Throwable {
776 jsr166 1.35 Thread.sleep(SMALL_DELAY_MS);
777 dl 1.1 }
778     }
779    
780 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
781     protected void realRun() {
782 dl 1.6 try {
783     Thread.sleep(SMALL_DELAY_MS);
784 jsr166 1.44 } catch (InterruptedException ok) {}
785 dl 1.6 }
786     }
787    
788 jsr166 1.45 public class SmallCallable extends CheckedCallable {
789     protected Object realCall() throws InterruptedException {
790 jsr166 1.35 Thread.sleep(SMALL_DELAY_MS);
791 dl 1.1 return Boolean.TRUE;
792     }
793     }
794    
795 jsr166 1.45 public class MediumRunnable extends CheckedRunnable {
796     protected void realRun() throws Throwable {
797 jsr166 1.35 Thread.sleep(MEDIUM_DELAY_MS);
798 dl 1.1 }
799     }
800    
801 jsr166 1.45 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
802     protected void realRun() throws InterruptedException {
803 jsr166 1.35 Thread.sleep(MEDIUM_DELAY_MS);
804 dl 1.1 }
805     }
806    
807 jsr166 1.45 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
808     protected void realRun() {
809 dl 1.1 try {
810     Thread.sleep(MEDIUM_DELAY_MS);
811 jsr166 1.44 } catch (InterruptedException ok) {}
812 dl 1.1 }
813     }
814 dl 1.5
815 jsr166 1.45 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
816     protected void realRun() {
817 dl 1.12 try {
818     Thread.sleep(LONG_DELAY_MS);
819 jsr166 1.44 } catch (InterruptedException ok) {}
820 dl 1.12 }
821     }
822    
823 dl 1.5 /**
824     * For use as ThreadFactory in constructors
825     */
826 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
827 jsr166 1.33 public Thread newThread(Runnable r) {
828 dl 1.5 return new Thread(r);
829 jsr166 1.27 }
830 dl 1.5 }
831    
832 jsr166 1.61 public interface TrackedRunnable extends Runnable {
833     boolean isDone();
834     }
835    
836     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
837     return new TrackedRunnable() {
838     private volatile boolean done = false;
839     public boolean isDone() { return done; }
840     public void run() {
841     try {
842     Thread.sleep(timeoutMillis);
843     done = true;
844     } catch (InterruptedException ok) {}
845     }
846     };
847     }
848    
849 jsr166 1.45 public static class TrackedShortRunnable implements Runnable {
850     public volatile boolean done = false;
851 dl 1.5 public void run() {
852     try {
853 jsr166 1.61 Thread.sleep(SHORT_DELAY_MS);
854     done = true;
855     } catch (InterruptedException ok) {}
856     }
857     }
858    
859     public static class TrackedSmallRunnable implements Runnable {
860     public volatile boolean done = false;
861     public void run() {
862     try {
863 dl 1.5 Thread.sleep(SMALL_DELAY_MS);
864     done = true;
865 jsr166 1.44 } catch (InterruptedException ok) {}
866 dl 1.6 }
867     }
868    
869 jsr166 1.45 public static class TrackedMediumRunnable implements Runnable {
870     public volatile boolean done = false;
871 dl 1.6 public void run() {
872     try {
873     Thread.sleep(MEDIUM_DELAY_MS);
874     done = true;
875 jsr166 1.44 } catch (InterruptedException ok) {}
876 dl 1.6 }
877     }
878    
879 jsr166 1.45 public static class TrackedLongRunnable implements Runnable {
880     public volatile boolean done = false;
881 dl 1.6 public void run() {
882     try {
883     Thread.sleep(LONG_DELAY_MS);
884     done = true;
885 jsr166 1.44 } catch (InterruptedException ok) {}
886 dl 1.6 }
887     }
888    
889 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
890     public volatile boolean done = false;
891 dl 1.6 public void run() {
892     done = true;
893 dl 1.5 }
894     }
895    
896 jsr166 1.45 public static class TrackedCallable implements Callable {
897     public volatile boolean done = false;
898 dl 1.5 public Object call() {
899     try {
900     Thread.sleep(SMALL_DELAY_MS);
901     done = true;
902 jsr166 1.44 } catch (InterruptedException ok) {}
903 dl 1.5 return Boolean.TRUE;
904     }
905     }
906 dl 1.14
907 jsr166 1.53 /**
908     * Analog of CheckedRunnable for RecursiveAction
909     */
910     public abstract class CheckedRecursiveAction extends RecursiveAction {
911     protected abstract void realCompute() throws Throwable;
912    
913     public final void compute() {
914     try {
915     realCompute();
916     } catch (Throwable t) {
917     threadUnexpectedException(t);
918     }
919     }
920     }
921    
922     /**
923     * Analog of CheckedCallable for RecursiveTask
924     */
925     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
926     protected abstract T realCompute() throws Throwable;
927    
928     public final T compute() {
929     try {
930     return realCompute();
931     } catch (Throwable t) {
932     threadUnexpectedException(t);
933     return null;
934     }
935     }
936     }
937 dl 1.5
938     /**
939     * For use as RejectedExecutionHandler in constructors
940     */
941 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
942 jsr166 1.35 public void rejectedExecution(Runnable r,
943     ThreadPoolExecutor executor) {}
944 dl 1.5 }
945 jsr166 1.27
946 jsr166 1.60 /**
947     * A CyclicBarrier that fails with AssertionFailedErrors instead
948     * of throwing checked exceptions.
949     */
950     public class CheckedBarrier extends CyclicBarrier {
951     public CheckedBarrier(int parties) { super(parties); }
952    
953     public int await() {
954     try {
955     return super.await();
956     } catch (Exception e) {
957     AssertionFailedError afe =
958     new AssertionFailedError("Unexpected exception: " + e);
959     afe.initCause(e);
960     throw afe;
961     }
962     }
963     }
964    
965 dl 1.1 }