ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.68
Committed: Sun Oct 31 18:33:47 2010 UTC (13 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.67: +1 -1 lines
Log Message:
whitespace

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