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.19 by dl, Sat Jan 10 20:37:20 2004 UTC vs.
Revision 1.60 by jsr166, Wed Oct 6 07:49:22 2010 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines