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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines