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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines