ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
(Generate patch)

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.2 by dl, Sat Sep 20 00:31:57 2003 UTC vs.
Revision 1.49 by jsr166, Tue Jan 5 02:08:37 2010 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
2 > * 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 > * Other contributors include Andrew Wright, Jeffrey Hayes,
6 > * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10   import java.util.*;
11   import java.util.concurrent.*;
12 + import static java.util.concurrent.TimeUnit.MILLISECONDS;
13   import java.io.*;
14 <
14 > import java.security.*;
15  
16   /**
17 < * Base class for JSR166 Junit TCK tests.  Defines some constants and
18 < * utility methods, as well as a simple framework for helping to make
19 < * sure that assertions failing in generated threads cause the
20 < * associated test that generated them to itself fail (which JUnit doe
21 < * not otherwise arrange).  The rules for creating such tests are:
17 > * Base class for JSR166 Junit TCK tests.  Defines some constants,
18 > * utility methods and classes, as well as a simple framework for
19 > * helping to make sure that assertions failing in generated threads
20 > * cause the associated test that generated them to itself fail (which
21 > * JUnit does not otherwise arrange).  The rules for creating such
22 > * tests are:
23   *
24   * <ol>
25   *
26   * <li> All assertions in code running in generated threads must use
27 < * the forms {@link threadFail} , {@link threadAssertTrue} {@link
28 < * threadAssertEquals}, or {@link threadAssertNull}, (not
27 > * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
28 > * #threadAssertEquals}, or {@link #threadAssertNull}, (not
29   * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
30   * particularly recommended) for other code to use these forms too.
31   * Only the most typically used JUnit assertion methods are defined
32   * this way, but enough to live with.</li>
33   *
34 < * <li> If you override {@link setUp} or {@link tearDown}, make sure
34 > * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
35   * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
36   * them. These methods are used to clear and check for thread
37   * assertion failures.</li>
38   *
39 < * <li>All delays and timeouts must use one of the constants {@link
40 < * SHORT_DELAY_MS}, {@link SMALL_DELAY_MS}, {@link MEDIUM_DELAY_MS},
41 < * {@link LONG_DELAY_MS}. The idea here is that a SHORT is always
42 < * discriminatable from zero time, and always allows enough time for
43 < * the small amounts of computation (creating a thread, calling a few
39 > * <li>All delays and timeouts must use one of the constants <tt>
40 > * SHORT_DELAY_MS</tt>, <tt> SMALL_DELAY_MS</tt>, <tt> MEDIUM_DELAY_MS</tt>,
41 > * <tt> LONG_DELAY_MS</tt>. The idea here is that a SHORT is always
42 > * discriminable from zero time, and always allows enough time for the
43 > * small amounts of computation (creating a thread, calling a few
44   * methods, etc) needed to reach a timeout point. Similarly, a SMALL
45   * is always discriminable as larger than SHORT and smaller than
46   * MEDIUM.  And so on. These constants are set to conservative values,
47   * but even so, if there is ever any doubt, they can all be increased
48 < * in one spot to rerun tests on slower platforms</li>
48 > * in one spot to rerun tests on slower platforms.</li>
49   *
50   * <li> All threads generated must be joined inside each test case
51   * method (or <tt>fail</tt> to do so) before returning from the
52 < * method. The {@link joinPool} method can be used to do this when
52 > * method. The <tt> joinPool</tt> method can be used to do this when
53   * using Executors.</li>
54   *
55   * </ol>
56 + *
57 + * <p> <b>Other notes</b>
58 + * <ul>
59 + *
60 + * <li> Usually, there is one testcase method per JSR166 method
61 + * covering "normal" operation, and then as many exception-testing
62 + * methods as there are exceptions the method can throw. Sometimes
63 + * there are multiple tests per JSR166 method when the different
64 + * "normal" behaviors differ significantly. And sometimes testcases
65 + * cover multiple methods when they cannot be tested in
66 + * isolation.</li>
67 + *
68 + * <li> The documentation style for testcases is to provide as javadoc
69 + * a simple sentence or two describing the property that the testcase
70 + * method purports to test. The javadocs do not say anything about how
71 + * the property is tested. To find out, read the code.</li>
72 + *
73 + * <li> These tests are "conformance tests", and do not attempt to
74 + * test throughput, latency, scalability or other performance factors
75 + * (see the separate "jtreg" tests for a set intended to check these
76 + * for the most central aspects of functionality.) So, most tests use
77 + * the smallest sensible numbers of threads, collection sizes, etc
78 + * needed to check basic conformance.</li>
79 + *
80 + * <li>The test classes currently do not declare inclusion in
81 + * any particular package to simplify things for people integrating
82 + * them in TCK test suites.</li>
83 + *
84 + * <li> As a convenience, the <tt>main</tt> of this class (JSR166TestCase)
85 + * runs all JSR166 unit tests.</li>
86 + *
87 + * </ul>
88   */
89   public class JSR166TestCase extends TestCase {
90 +    private static final boolean useSecurityManager =
91 +        Boolean.getBoolean("jsr166.useSecurityManager");
92 +
93 +    /**
94 +     * Runs all JSR166 unit tests using junit.textui.TestRunner
95 +     */
96 +    public static void main(String[] args) {
97 +        if (useSecurityManager) {
98 +            System.err.println("Setting a permissive security manager");
99 +            Policy.setPolicy(permissivePolicy());
100 +            System.setSecurityManager(new SecurityManager());
101 +        }
102 +        int iters = 1;
103 +        if (args.length > 0)
104 +            iters = Integer.parseInt(args[0]);
105 +        Test s = suite();
106 +        for (int i = 0; i < iters; ++i) {
107 +            junit.textui.TestRunner.run(s);
108 +            System.gc();
109 +            System.runFinalization();
110 +        }
111 +        System.exit(0);
112 +    }
113 +
114 +    /**
115 +     * Collects all JSR166 unit tests as one suite
116 +     */
117 +    public static Test suite() {
118 +        TestSuite suite = new TestSuite("JSR166 Unit Tests");
119 +
120 +        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
121 +        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
122 +        suite.addTest(new TestSuite(RecursiveActionTest.class));
123 +        suite.addTest(new TestSuite(RecursiveTaskTest.class));
124 +        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
125 +        suite.addTest(new TestSuite(PhaserTest.class));
126 +        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
127 +        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
128 +        suite.addTest(new TestSuite(AbstractQueueTest.class));
129 +        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
130 +        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
131 +        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
132 +        suite.addTest(new TestSuite(ArrayDequeTest.class));
133 +        suite.addTest(new TestSuite(AtomicBooleanTest.class));
134 +        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
135 +        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
136 +        suite.addTest(new TestSuite(AtomicIntegerTest.class));
137 +        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
138 +        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
139 +        suite.addTest(new TestSuite(AtomicLongTest.class));
140 +        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
141 +        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
142 +        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
143 +        suite.addTest(new TestSuite(AtomicReferenceTest.class));
144 +        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
145 +        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
146 +        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
147 +        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
148 +        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
149 +        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
150 +        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
151 +        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
152 +        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
153 +        suite.addTest(new TestSuite(CountDownLatchTest.class));
154 +        suite.addTest(new TestSuite(CyclicBarrierTest.class));
155 +        suite.addTest(new TestSuite(DelayQueueTest.class));
156 +        suite.addTest(new TestSuite(EntryTest.class));
157 +        suite.addTest(new TestSuite(ExchangerTest.class));
158 +        suite.addTest(new TestSuite(ExecutorsTest.class));
159 +        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
160 +        suite.addTest(new TestSuite(FutureTaskTest.class));
161 +        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
162 +        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
163 +        suite.addTest(new TestSuite(LinkedListTest.class));
164 +        suite.addTest(new TestSuite(LockSupportTest.class));
165 +        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
166 +        suite.addTest(new TestSuite(PriorityQueueTest.class));
167 +        suite.addTest(new TestSuite(ReentrantLockTest.class));
168 +        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
169 +        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
170 +        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
171 +        suite.addTest(new TestSuite(SemaphoreTest.class));
172 +        suite.addTest(new TestSuite(SynchronousQueueTest.class));
173 +        suite.addTest(new TestSuite(SystemTest.class));
174 +        suite.addTest(new TestSuite(ThreadLocalTest.class));
175 +        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
176 +        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
177 +        suite.addTest(new TestSuite(ThreadTest.class));
178 +        suite.addTest(new TestSuite(TimeUnitTest.class));
179 +        suite.addTest(new TestSuite(TreeMapTest.class));
180 +        suite.addTest(new TestSuite(TreeSetTest.class));
181 +        suite.addTest(new TestSuite(TreeSubMapTest.class));
182 +        suite.addTest(new TestSuite(TreeSubSetTest.class));
183 +
184 +        return suite;
185 +    }
186 +
187  
188      public static long SHORT_DELAY_MS;
189      public static long SMALL_DELAY_MS;
# Line 60 | Line 192 | public class JSR166TestCase extends Test
192  
193  
194      /**
195 <     * Return the shortest timed delay. This could
196 <     * be reimplmented to use for example a Property.
197 <     */
195 >     * Returns the shortest timed delay. This could
196 >     * be reimplemented to use for example a Property.
197 >     */
198      protected long getShortDelay() {
199          return 50;
200      }
201  
202  
203      /**
204 <     * Set delays as multiples fo SHORT_DELAY.
204 >     * Sets delays as multiples of SHORT_DELAY.
205       */
206 <    protected  void setDelays() {
206 >    protected void setDelays() {
207          SHORT_DELAY_MS = getShortDelay();
208          SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
209          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
# Line 81 | Line 213 | public class JSR166TestCase extends Test
213      /**
214       * Flag set true if any threadAssert methods fail
215       */
216 <    protected volatile boolean threadFailed;
216 >    volatile boolean threadFailed;
217  
218      /**
219 <     * Initialize test to indicat that no thread assertions have failed
219 >     * Initializes test to indicate that no thread assertions have failed
220       */
221 <    public void setUp() {
221 >    public void setUp() {
222          setDelays();
223 <        threadFailed = false;  
223 >        threadFailed = false;
224      }
225  
226      /**
227 <     * Trigger test case failure if any thread assertions have failed
227 >     * Triggers test case failure if any thread assertions have failed
228       */
229 <    public void tearDown() {
230 <        assertFalse(threadFailed);  
229 >    public void tearDown() {
230 >        assertFalse(threadFailed);
231      }
232  
233 +    /**
234 +     * Fail, also setting status to indicate current testcase should fail
235 +     */
236      public void threadFail(String reason) {
237          threadFailed = true;
238          fail(reason);
239      }
240  
241 +    /**
242 +     * If expression not true, set status to indicate current testcase
243 +     * should fail
244 +     */
245      public void threadAssertTrue(boolean b) {
246          if (!b) {
247              threadFailed = true;
248              assertTrue(b);
249          }
250      }
251 +
252 +    /**
253 +     * If expression not false, set status to indicate current testcase
254 +     * should fail
255 +     */
256      public void threadAssertFalse(boolean b) {
257          if (b) {
258              threadFailed = true;
259              assertFalse(b);
260          }
261      }
262 +
263 +    /**
264 +     * If argument not null, set status to indicate current testcase
265 +     * should fail
266 +     */
267      public void threadAssertNull(Object x) {
268          if (x != null) {
269              threadFailed = true;
270              assertNull(x);
271          }
272      }
273 +
274 +    /**
275 +     * If arguments not equal, set status to indicate current testcase
276 +     * should fail
277 +     */
278      public void threadAssertEquals(long x, long y) {
279          if (x != y) {
280              threadFailed = true;
281              assertEquals(x, y);
282          }
283      }
284 +
285 +    /**
286 +     * If arguments not equal, set status to indicate current testcase
287 +     * should fail
288 +     */
289      public void threadAssertEquals(Object x, Object y) {
290          if (x != y && (x == null || !x.equals(y))) {
291              threadFailed = true;
# Line 135 | Line 294 | public class JSR166TestCase extends Test
294      }
295  
296      /**
297 +     * threadFail with message "should throw exception"
298 +     */
299 +    public void threadShouldThrow() {
300 +        threadFailed = true;
301 +        fail("should throw exception");
302 +    }
303 +
304 +    /**
305 +     * threadFail with message "should throw" + exceptionName
306 +     */
307 +    public void threadShouldThrow(String exceptionName) {
308 +        threadFailed = true;
309 +        fail("should throw " + exceptionName);
310 +    }
311 +
312 +    /**
313 +     * threadFail with message "Unexpected exception"
314 +     */
315 +    public void threadUnexpectedException() {
316 +        threadFailed = true;
317 +        fail("Unexpected exception");
318 +    }
319 +
320 +    /**
321 +     * threadFail with message "Unexpected exception", with argument
322 +     */
323 +    public void threadUnexpectedException(Throwable ex) {
324 +        threadFailed = true;
325 +        ex.printStackTrace();
326 +        fail("Unexpected exception: " + ex);
327 +    }
328 +
329 +    /**
330       * Wait out termination of a thread pool or fail doing so
331       */
332      public void joinPool(ExecutorService exec) {
333          try {
334              exec.shutdown();
335 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
336 <        } catch(InterruptedException ie) {
337 <            fail("unexpected exception");
335 >            assertTrue(exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
336 >        } catch (SecurityException ok) {
337 >            // Allowed in case test doesn't have privs
338 >        } catch (InterruptedException ie) {
339 >            fail("Unexpected InterruptedException");
340          }
341      }
342  
343  
344 +    /**
345 +     * fail with message "should throw exception"
346 +     */
347 +    public void shouldThrow() {
348 +        fail("Should throw exception");
349 +    }
350 +
351 +    /**
352 +     * fail with message "should throw " + exceptionName
353 +     */
354 +    public void shouldThrow(String exceptionName) {
355 +        fail("Should throw " + exceptionName);
356 +    }
357 +
358 +    /**
359 +     * fail with message "Unexpected exception"
360 +     */
361 +    public void unexpectedException() {
362 +        fail("Unexpected exception");
363 +    }
364 +
365 +    /**
366 +     * fail with message "Unexpected exception", with argument
367 +     */
368 +    public void unexpectedException(Throwable ex) {
369 +        ex.printStackTrace();
370 +        fail("Unexpected exception: " + ex);
371 +    }
372 +
373  
374      /**
375       * The number of elements to place in collections, arrays, etc.
# Line 155 | Line 378 | public class JSR166TestCase extends Test
378  
379      // Some convenient Integer constants
380  
381 <    public static final Integer zero = new Integer(0);
382 <    public static final Integer one = new Integer(1);
383 <    public static final Integer two = new Integer(2);
384 <    public static final Integer three  = new Integer(3);
381 >    public static final Integer zero  = new Integer(0);
382 >    public static final Integer one   = new Integer(1);
383 >    public static final Integer two   = new Integer(2);
384 >    public static final Integer three = new Integer(3);
385      public static final Integer four  = new Integer(4);
386      public static final Integer five  = new Integer(5);
387 <    public static final Integer six = new Integer(6);
387 >    public static final Integer six   = new Integer(6);
388      public static final Integer seven = new Integer(7);
389      public static final Integer eight = new Integer(8);
390 <    public static final Integer nine = new Integer(9);
390 >    public static final Integer nine  = new Integer(9);
391      public static final Integer m1  = new Integer(-1);
392      public static final Integer m2  = new Integer(-2);
393      public static final Integer m3  = new Integer(-3);
394 <    public static final Integer m4 = new Integer(-4);
395 <    public static final Integer m5 = new Integer(-5);
394 >    public static final Integer m4  = new Integer(-4);
395 >    public static final Integer m5  = new Integer(-5);
396 >    public static final Integer m6  = new Integer(-6);
397      public static final Integer m10 = new Integer(-10);
398  
399  
400 <    // Some convenient Runnable classes
400 >    /**
401 >     * Runs Runnable r with a security policy that permits precisely
402 >     * the specified permissions.  If there is no current security
403 >     * manager, the runnable is run twice, both with and without a
404 >     * security manager.  We require that any security manager permit
405 >     * getPolicy/setPolicy.
406 >     */
407 >    public void runWithPermissions(Runnable r, Permission... permissions) {
408 >        SecurityManager sm = System.getSecurityManager();
409 >        if (sm == null) {
410 >            r.run();
411 >            Policy savedPolicy = Policy.getPolicy();
412 >            try {
413 >                Policy.setPolicy(permissivePolicy());
414 >                System.setSecurityManager(new SecurityManager());
415 >                runWithPermissions(r, permissions);
416 >            } finally {
417 >                System.setSecurityManager(null);
418 >                Policy.setPolicy(savedPolicy);
419 >            }
420 >        } else {
421 >            Policy savedPolicy = Policy.getPolicy();
422 >            AdjustablePolicy policy = new AdjustablePolicy(permissions);
423 >            Policy.setPolicy(policy);
424  
425 <    public static class NoOpRunnable implements Runnable {
426 <        public void run() {}
425 >            try {
426 >                r.run();
427 >            } finally {
428 >                policy.addPermission(new SecurityPermission("setPolicy"));
429 >                Policy.setPolicy(savedPolicy);
430 >            }
431 >        }
432      }
433  
434 <    public static class NoOpCallable implements Callable {
435 <        public Object call() { return Boolean.TRUE; }
434 >    /**
435 >     * Runs a runnable without any permissions.
436 >     */
437 >    public void runWithoutPermissions(Runnable r) {
438 >        runWithPermissions(r);
439      }
440  
441 <    public class ShortRunnable implements Runnable {
442 <        public void run() {
441 >    /**
442 >     * A security policy where new permissions can be dynamically added
443 >     * or all cleared.
444 >     */
445 >    public static class AdjustablePolicy extends java.security.Policy {
446 >        Permissions perms = new Permissions();
447 >        AdjustablePolicy(Permission... permissions) {
448 >            for (Permission permission : permissions)
449 >                perms.add(permission);
450 >        }
451 >        void addPermission(Permission perm) { perms.add(perm); }
452 >        void clearPermissions() { perms = new Permissions(); }
453 >        public PermissionCollection getPermissions(CodeSource cs) {
454 >            return perms;
455 >        }
456 >        public PermissionCollection getPermissions(ProtectionDomain pd) {
457 >            return perms;
458 >        }
459 >        public boolean implies(ProtectionDomain pd, Permission p) {
460 >            return perms.implies(p);
461 >        }
462 >        public void refresh() {}
463 >    }
464 >
465 >    /**
466 >     * Returns a policy containing all the permissions we ever need.
467 >     */
468 >    public static Policy permissivePolicy() {
469 >        return new AdjustablePolicy
470 >            // Permissions j.u.c. needs directly
471 >            (new RuntimePermission("modifyThread"),
472 >             new RuntimePermission("getClassLoader"),
473 >             new RuntimePermission("setContextClassLoader"),
474 >             // Permissions needed to change permissions!
475 >             new SecurityPermission("getPolicy"),
476 >             new SecurityPermission("setPolicy"),
477 >             new RuntimePermission("setSecurityManager"),
478 >             // Permissions needed by the junit test harness
479 >             new RuntimePermission("accessDeclaredMembers"),
480 >             new PropertyPermission("*", "read"),
481 >             new java.io.FilePermission("<<ALL FILES>>", "read"));
482 >    }
483 >
484 >    /**
485 >     * Sleep until the timeout has elapsed, or interrupted.
486 >     * Does <em>NOT</em> throw InterruptedException.
487 >     */
488 >    void sleepTillInterrupted(long timeoutMillis) {
489 >        try {
490 >            Thread.sleep(timeoutMillis);
491 >        } catch (InterruptedException wakeup) {}
492 >    }
493 >
494 >    /**
495 >     * Returns a new started Thread running the given runnable.
496 >     */
497 >    Thread newStartedThread(Runnable runnable) {
498 >        Thread t = new Thread(runnable);
499 >        t.start();
500 >        return t;
501 >    }
502 >
503 >    // Some convenient Runnable classes
504 >
505 >    public abstract class CheckedRunnable implements Runnable {
506 >        protected abstract void realRun() throws Throwable;
507 >
508 >        public final void run() {
509              try {
510 <                Thread.sleep(SHORT_DELAY_MS);
510 >                realRun();
511 >            } catch (Throwable t) {
512 >                threadUnexpectedException(t);
513              }
514 <            catch(Exception e) {
515 <                threadFail("unexpectedException");
514 >        }
515 >    }
516 >
517 >    public abstract class RunnableShouldThrow implements Runnable {
518 >        protected abstract void realRun() throws Throwable;
519 >
520 >        final Class<?> exceptionClass;
521 >
522 >        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
523 >            this.exceptionClass = exceptionClass;
524 >        }
525 >
526 >        public final void run() {
527 >            try {
528 >                realRun();
529 >                threadShouldThrow(exceptionClass.getSimpleName());
530 >            } catch (Throwable t) {
531 >                if (! exceptionClass.isInstance(t))
532 >                    threadUnexpectedException(t);
533              }
534          }
535      }
536  
537 <    public class ShortInterruptedRunnable implements Runnable {
538 <        public void run() {
537 >    public abstract class ThreadShouldThrow extends Thread {
538 >        protected abstract void realRun() throws Throwable;
539 >
540 >        final Class<?> exceptionClass;
541 >
542 >        <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
543 >            this.exceptionClass = exceptionClass;
544 >        }
545 >
546 >        public final void run() {
547              try {
548 <                Thread.sleep(SHORT_DELAY_MS);
549 <                threadFail("should throw IE");
548 >                realRun();
549 >                threadShouldThrow(exceptionClass.getSimpleName());
550 >            } catch (Throwable t) {
551 >                if (! exceptionClass.isInstance(t))
552 >                    threadUnexpectedException(t);
553              }
554 <            catch(InterruptedException success) {
554 >        }
555 >    }
556 >
557 >    public abstract class CheckedInterruptedRunnable implements Runnable {
558 >        protected abstract void realRun() throws Throwable;
559 >
560 >        public final void run() {
561 >            try {
562 >                realRun();
563 >                threadShouldThrow("InterruptedException");
564 >            } catch (InterruptedException success) {
565 >            } catch (Throwable t) {
566 >                threadUnexpectedException(t);
567              }
568          }
569      }
570  
571 <    public class SmallRunnable implements Runnable {
572 <        public void run() {
571 >    public abstract class CheckedCallable<T> implements Callable<T> {
572 >        protected abstract T realCall() throws Throwable;
573 >
574 >        public final T call() {
575              try {
576 <                Thread.sleep(SMALL_DELAY_MS);
576 >                return realCall();
577 >            } catch (Throwable t) {
578 >                threadUnexpectedException(t);
579              }
580 <            catch(Exception e) {
581 <                threadFail("unexpectedException");
580 >            return null;
581 >        }
582 >    }
583 >
584 >    public abstract class CheckedInterruptedCallable<T> implements Callable<T> {
585 >        protected abstract T realCall() throws Throwable;
586 >
587 >        public final T call() {
588 >            try {
589 >                T result = realCall();
590 >                threadShouldThrow("InterruptedException");
591 >                return result;
592 >            } catch (InterruptedException success) {
593 >            } catch (Throwable t) {
594 >                threadUnexpectedException(t);
595              }
596 +            return null;
597          }
598      }
599  
600 <    public class SmallCallable implements Callable {
601 <        public Object call() {
600 >    public static class NoOpRunnable implements Runnable {
601 >        public void run() {}
602 >    }
603 >
604 >    public static class NoOpCallable implements Callable {
605 >        public Object call() { return Boolean.TRUE; }
606 >    }
607 >
608 >    public static final String TEST_STRING = "a test string";
609 >
610 >    public static class StringTask implements Callable<String> {
611 >        public String call() { return TEST_STRING; }
612 >    }
613 >
614 >    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
615 >        return new CheckedCallable<String>() {
616 >            public String realCall() {
617 >                try {
618 >                    latch.await();
619 >                } catch (InterruptedException quittingTime) {}
620 >                return TEST_STRING;
621 >            }};
622 >    }
623 >
624 >    public static class NPETask implements Callable<String> {
625 >        public String call() { throw new NullPointerException(); }
626 >    }
627 >
628 >    public static class CallableOne implements Callable<Integer> {
629 >        public Integer call() { return one; }
630 >    }
631 >
632 >    public class ShortRunnable extends CheckedRunnable {
633 >        protected void realRun() throws Throwable {
634 >            Thread.sleep(SHORT_DELAY_MS);
635 >        }
636 >    }
637 >
638 >    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
639 >        protected void realRun() throws InterruptedException {
640 >            Thread.sleep(SHORT_DELAY_MS);
641 >        }
642 >    }
643 >
644 >    public class SmallRunnable extends CheckedRunnable {
645 >        protected void realRun() throws Throwable {
646 >            Thread.sleep(SMALL_DELAY_MS);
647 >        }
648 >    }
649 >
650 >    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
651 >        protected void realRun() {
652              try {
653                  Thread.sleep(SMALL_DELAY_MS);
654 <            }
655 <            catch(Exception e) {
656 <                threadFail("unexpectedException");
657 <            }
654 >            } catch (InterruptedException ok) {}
655 >        }
656 >    }
657 >
658 >    public class SmallCallable extends CheckedCallable {
659 >        protected Object realCall() throws InterruptedException {
660 >            Thread.sleep(SMALL_DELAY_MS);
661              return Boolean.TRUE;
662          }
663      }
664  
665 <    public class SmallInterruptedRunnable implements Runnable {
665 >    public class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
666 >        protected void realRun() throws InterruptedException {
667 >            Thread.sleep(SMALL_DELAY_MS);
668 >        }
669 >    }
670 >
671 >    public class MediumRunnable extends CheckedRunnable {
672 >        protected void realRun() throws Throwable {
673 >            Thread.sleep(MEDIUM_DELAY_MS);
674 >        }
675 >    }
676 >
677 >    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
678 >        protected void realRun() throws InterruptedException {
679 >            Thread.sleep(MEDIUM_DELAY_MS);
680 >        }
681 >    }
682 >
683 >    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
684 >        protected void realRun() {
685 >            try {
686 >                Thread.sleep(MEDIUM_DELAY_MS);
687 >            } catch (InterruptedException ok) {}
688 >        }
689 >    }
690 >
691 >    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
692 >        protected void realRun() {
693 >            try {
694 >                Thread.sleep(LONG_DELAY_MS);
695 >            } catch (InterruptedException ok) {}
696 >        }
697 >    }
698 >
699 >    /**
700 >     * For use as ThreadFactory in constructors
701 >     */
702 >    public static class SimpleThreadFactory implements ThreadFactory {
703 >        public Thread newThread(Runnable r) {
704 >            return new Thread(r);
705 >        }
706 >    }
707 >
708 >    public static class TrackedShortRunnable implements Runnable {
709 >        public volatile boolean done = false;
710          public void run() {
711              try {
712                  Thread.sleep(SMALL_DELAY_MS);
713 <                threadFail("should throw IE");
714 <            }
237 <            catch(InterruptedException success) {
238 <            }
713 >                done = true;
714 >            } catch (InterruptedException ok) {}
715          }
716      }
717  
718 <
719 <    public class MediumRunnable implements Runnable {
718 >    public static class TrackedMediumRunnable implements Runnable {
719 >        public volatile boolean done = false;
720          public void run() {
721              try {
722                  Thread.sleep(MEDIUM_DELAY_MS);
723 <            }
724 <            catch(Exception e) {
249 <                threadFail("unexpectedException");
250 <            }
723 >                done = true;
724 >            } catch (InterruptedException ok) {}
725          }
726      }
727  
728 <    public class MediumInterruptedRunnable implements Runnable {
728 >    public static class TrackedLongRunnable implements Runnable {
729 >        public volatile boolean done = false;
730          public void run() {
731              try {
732 <                Thread.sleep(MEDIUM_DELAY_MS);
733 <                threadFail("should throw IE");
734 <            }
260 <            catch(InterruptedException success) {
261 <            }
732 >                Thread.sleep(LONG_DELAY_MS);
733 >                done = true;
734 >            } catch (InterruptedException ok) {}
735          }
736      }
737  
738 <    public class MediumPossiblyInterruptedRunnable implements Runnable {
738 >    public static class TrackedNoOpRunnable implements Runnable {
739 >        public volatile boolean done = false;
740          public void run() {
741 +            done = true;
742 +        }
743 +    }
744 +
745 +    public static class TrackedCallable implements Callable {
746 +        public volatile boolean done = false;
747 +        public Object call() {
748              try {
749 <                Thread.sleep(MEDIUM_DELAY_MS);
750 <            }
751 <            catch(InterruptedException success) {
752 <            }
749 >                Thread.sleep(SMALL_DELAY_MS);
750 >                done = true;
751 >            } catch (InterruptedException ok) {}
752 >            return Boolean.TRUE;
753          }
754      }
755 <    
755 >
756 >
757 >    /**
758 >     * For use as RejectedExecutionHandler in constructors
759 >     */
760 >    public static class NoOpREHandler implements RejectedExecutionHandler {
761 >        public void rejectedExecution(Runnable r,
762 >                                      ThreadPoolExecutor executor) {}
763 >    }
764 >
765   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines