ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.58
Committed: Wed Oct 6 02:11:57 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.57: +2 -1 lines
Log Message:
prefer daemon threads

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