ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.65
Committed: Thu Oct 21 23:22:49 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.64: +18 -0 lines
Log Message:
add waitForThreadToEnterWaitState

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