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.39 by jsr166, Tue Nov 17 21:51:45 2009 UTC vs.
Revision 1.61 by jsr166, Mon Oct 11 03:54:10 2010 UTC

# Line 7 | Line 7
7   */
8  
9   import junit.framework.*;
10 < import java.util.*;
10 > import java.util.PropertyPermission;
11   import java.util.concurrent.*;
12 + import java.util.concurrent.atomic.AtomicReference;
13   import static java.util.concurrent.TimeUnit.MILLISECONDS;
14 < import java.io.*;
15 < import java.security.*;
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,
# Line 26 | Line 32 | import java.security.*;
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
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
# Line 48 | Line 54 | import java.security.*;
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 81 | 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 +     * 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 <        int iters = 1;
137 <        if (args.length > 0)
138 <            iters = Integer.parseInt(args[0]);
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);
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
166 >     * Collects all JSR166 unit tests as one suite.
167       */
168 <    public static Test suite ( ) {
169 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
170 <
171 <        suite.addTest(new TestSuite(ForkJoinPoolTest.class));
172 <        suite.addTest(new TestSuite(ForkJoinTaskTest.class));
173 <        suite.addTest(new TestSuite(RecursiveActionTest.class));
174 <        suite.addTest(new TestSuite(RecursiveTaskTest.class));
175 <        suite.addTest(new TestSuite(LinkedTransferQueueTest.class));
176 <        suite.addTest(new TestSuite(PhaserTest.class));
177 <        suite.addTest(new TestSuite(ThreadLocalRandomTest.class));
178 <        suite.addTest(new TestSuite(AbstractExecutorServiceTest.class));
179 <        suite.addTest(new TestSuite(AbstractQueueTest.class));
180 <        suite.addTest(new TestSuite(AbstractQueuedSynchronizerTest.class));
181 <        suite.addTest(new TestSuite(AbstractQueuedLongSynchronizerTest.class));
182 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
183 <        suite.addTest(new TestSuite(ArrayDequeTest.class));
184 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
185 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
186 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
187 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
188 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
189 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
190 <        suite.addTest(new TestSuite(AtomicLongTest.class));
191 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
192 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
193 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
194 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
195 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
196 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
197 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
198 <        suite.addTest(new TestSuite(ConcurrentSkipListMapTest.class));
199 <        suite.addTest(new TestSuite(ConcurrentSkipListSubMapTest.class));
200 <        suite.addTest(new TestSuite(ConcurrentSkipListSetTest.class));
201 <        suite.addTest(new TestSuite(ConcurrentSkipListSubSetTest.class));
202 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
203 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
204 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
205 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
206 <        suite.addTest(new TestSuite(DelayQueueTest.class));
207 <        suite.addTest(new TestSuite(EntryTest.class));
208 <        suite.addTest(new TestSuite(ExchangerTest.class));
209 <        suite.addTest(new TestSuite(ExecutorsTest.class));
210 <        suite.addTest(new TestSuite(ExecutorCompletionServiceTest.class));
211 <        suite.addTest(new TestSuite(FutureTaskTest.class));
212 <        suite.addTest(new TestSuite(LinkedBlockingDequeTest.class));
213 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
214 <        suite.addTest(new TestSuite(LinkedListTest.class));
215 <        suite.addTest(new TestSuite(LockSupportTest.class));
216 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
217 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
218 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
219 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
220 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
221 <        suite.addTest(new TestSuite(ScheduledExecutorSubclassTest.class));
222 <        suite.addTest(new TestSuite(SemaphoreTest.class));
223 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
224 <        suite.addTest(new TestSuite(SystemTest.class));
225 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
226 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
227 <        suite.addTest(new TestSuite(ThreadPoolExecutorSubclassTest.class));
228 <        suite.addTest(new TestSuite(ThreadTest.class));
229 <        suite.addTest(new TestSuite(TimeUnitTest.class));
230 <        suite.addTest(new TestSuite(TreeMapTest.class));
231 <        suite.addTest(new TestSuite(TreeSetTest.class));
232 <        suite.addTest(new TestSuite(TreeSubMapTest.class));
233 <        suite.addTest(new TestSuite(TreeSubSetTest.class));
175 <
176 <        return suite;
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  
# Line 195 | Line 252 | public class JSR166TestCase extends Test
252      /**
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 <    volatile boolean threadFailed;
265 >    private final AtomicReference<Throwable> threadFailure
266 >        = new AtomicReference<Throwable>(null);
267  
268      /**
269 <     * Initializes test to indicate 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 threadRecordFailure(Throwable t) {
275 +        threadFailure.compareAndSet(null, t);
276 +    }
277 +
278      public void setUp() {
279          setDelays();
215        threadFailed = false;
280      }
281  
282      /**
283 <     * Triggers test case failure if any thread assertions have failed
284 <     */
285 <    public void tearDown() {
286 <        assertFalse(threadFailed);
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() 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 <     * Fail, also setting status to indicate current testcase should fail
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 <     * If expression not true, set status to indicate current testcase
321 <     * should fail
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) {
239 <            threadFailed = true;
325 >        try {
326              assertTrue(b);
327 +        } catch (AssertionFailedError t) {
328 +            threadRecordFailure(t);
329 +            throw t;
330          }
331      }
332  
333      /**
334 <     * If expression not false, set status to indicate current testcase
335 <     * should fail
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) {
250 <            threadFailed = true;
339 >        try {
340              assertFalse(b);
341 +        } catch (AssertionFailedError t) {
342 +            threadRecordFailure(t);
343 +            throw t;
344          }
345      }
346  
347      /**
348 <     * If argument not null, set status to indicate current testcase
349 <     * should fail
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) {
261 <            threadFailed = true;
353 >        try {
354              assertNull(x);
355 +        } catch (AssertionFailedError t) {
356 +            threadRecordFailure(t);
357 +            throw t;
358          }
359      }
360  
361      /**
362 <     * If arguments not equal, set status to indicate current testcase
363 <     * should fail
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) {
272 <            threadFailed = true;
367 >        try {
368              assertEquals(x, y);
369 +        } catch (AssertionFailedError t) {
370 +            threadRecordFailure(t);
371 +            throw t;
372          }
373      }
374  
375      /**
376 <     * If arguments not equal, set status to indicate current testcase
377 <     * should fail
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))) {
283 <            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 <     * threadFail with message "should throw exception"
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;
293 <        fail("should throw exception");
409 >        threadFail("should throw exception");
410      }
411  
412      /**
413 <     * threadFail with message "Unexpected exception"
413 >     * Calls threadFail with message "should throw" + exceptionName.
414       */
415 <    public void threadUnexpectedException() {
416 <        threadFailed = true;
301 <        fail("Unexpected exception");
415 >    public void threadShouldThrow(String exceptionName) {
416 >        threadFail("should throw " + exceptionName);
417      }
418  
419      /**
420 <     * threadFail with message "Unexpected exception", with argument
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 ex) {
425 <        threadFailed = true;
426 <        ex.printStackTrace();
427 <        fail("Unexpected exception: " + ex);
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, MILLISECONDS));
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 exception");
450 >            fail("Unexpected InterruptedException");
451          }
452      }
453  
454  
455      /**
456 <     * fail with message "should throw exception"
456 >     * Fails with message "should throw exception".
457       */
458      public void shouldThrow() {
459          fail("Should throw exception");
460      }
461  
462      /**
463 <     * fail with message "Unexpected exception"
463 >     * Fails with message "should throw " + exceptionName.
464       */
465 <    public void unexpectedException() {
466 <        fail("Unexpected exception");
465 >    public void shouldThrow(String exceptionName) {
466 >        fail("Should throw " + exceptionName);
467      }
468  
469      /**
343     * fail with message "Unexpected exception", with argument
344     */
345    public void unexpectedException(Throwable ex) {
346        ex.printStackTrace();
347        fail("Unexpected exception: " + ex);
348    }
349
350
351    /**
470       * The number of elements to place in collections, arrays, etc.
471       */
472 <    static final int SIZE = 20;
472 >    public static final int SIZE = 20;
473  
474      // Some convenient Integer constants
475  
476 <    static final Integer zero = new Integer(0);
477 <    static final Integer one = new Integer(1);
478 <    static final Integer two = new Integer(2);
479 <    static final Integer three  = new Integer(3);
480 <    static final Integer four  = new Integer(4);
481 <    static final Integer five  = new Integer(5);
482 <    static final Integer six = new Integer(6);
483 <    static final Integer seven = new Integer(7);
484 <    static final Integer eight = new Integer(8);
485 <    static final Integer nine = new Integer(9);
486 <    static final Integer m1  = new Integer(-1);
487 <    static final Integer m2  = new Integer(-2);
488 <    static final Integer m3  = new Integer(-3);
489 <    static final Integer m4 = new Integer(-4);
490 <    static final Integer m5 = new Integer(-5);
491 <    static final Integer m6 = new Integer(-6);
492 <    static final Integer m10 = new Integer(-10);
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);
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);
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);
491 >    public static final Integer m6  = new Integer(-6);
492 >    public static final Integer m10 = new Integer(-10);
493  
494  
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 +            try {
521 +                r.run();
522 +            } finally {
523 +                policy.addPermission(new SecurityPermission("setPolicy"));
524 +                Policy.setPolicy(savedPolicy);
525 +            }
526 +        }
527 +    }
528 +
529 +    /**
530 +     * Runs a runnable without any permissions.
531 +     */
532 +    public void runWithoutPermissions(Runnable r) {
533 +        runWithPermissions(r);
534 +    }
535 +
536 +    /**
537       * A security policy where new permissions can be dynamically added
538       * or all cleared.
539       */
540 <    static class AdjustablePolicy extends java.security.Policy {
540 >    public static class AdjustablePolicy extends java.security.Policy {
541          Permissions perms = new Permissions();
542 <        AdjustablePolicy() { }
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() {}
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 <     * Sleep until the timeout has elapsed, or interrupted.
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) {
406 <        }
601 >        } catch (InterruptedException wakeup) {}
602      }
603  
604      /**
605 <     * Returns a new started Thread running the given runnable.
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 <    abstract class CheckedRunnable implements Runnable {
635 <        abstract void realRun() throws Throwable;
634 >    public abstract class CheckedRunnable implements Runnable {
635 >        protected abstract void realRun() throws Throwable;
636  
637          public final void run() {
638              try {
# Line 429 | Line 643 | public class JSR166TestCase extends Test
643          }
644      }
645  
646 <    abstract class CheckedInterruptedRunnable implements Runnable {
647 <        abstract void realRun() throws Throwable;
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();
658 >                threadShouldThrow(exceptionClass.getSimpleName());
659 >            } catch (Throwable t) {
660 >                if (! exceptionClass.isInstance(t))
661 >                    threadUnexpectedException(t);
662 >            }
663 >        }
664 >    }
665 >
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 >                realRun();
678 >                threadShouldThrow(exceptionClass.getSimpleName());
679 >            } catch (Throwable t) {
680 >                if (! exceptionClass.isInstance(t))
681 >                    threadUnexpectedException(t);
682 >            }
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);
# Line 443 | Line 697 | public class JSR166TestCase extends Test
697          }
698      }
699  
700 <    abstract class CheckedCallable<T> implements Callable<T> {
701 <        abstract T realCall() throws Throwable;
700 >    public abstract class CheckedCallable<T> implements Callable<T> {
701 >        protected abstract T realCall() throws Throwable;
702  
703          public final T call() {
704              try {
# Line 456 | Line 710 | public class JSR166TestCase extends Test
710          }
711      }
712  
713 <    static class NoOpRunnable implements Runnable {
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 static class NoOpRunnable implements Runnable {
731          public void run() {}
732      }
733  
734 <    static class NoOpCallable implements Callable {
734 >    public static class NoOpCallable implements Callable {
735          public Object call() { return Boolean.TRUE; }
736      }
737  
738 <    static final String TEST_STRING = "a test string";
738 >    public static final String TEST_STRING = "a test string";
739  
740 <    static class StringTask implements Callable<String> {
740 >    public static class StringTask implements Callable<String> {
741          public String call() { return TEST_STRING; }
742      }
743  
744 <    static class NPETask implements Callable<String> {
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 <    static class CallableOne implements Callable<Integer> {
758 >    public static class CallableOne implements Callable<Integer> {
759          public Integer call() { return one; }
760      }
761  
762 <    class ShortRunnable extends CheckedRunnable {
763 <        void realRun() throws Throwable {
762 >    public class ShortRunnable extends CheckedRunnable {
763 >        protected void realRun() throws Throwable {
764              Thread.sleep(SHORT_DELAY_MS);
765          }
766      }
767  
768 <    class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
769 <        void realRun() throws InterruptedException {
768 >    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
769 >        protected void realRun() throws InterruptedException {
770              Thread.sleep(SHORT_DELAY_MS);
771          }
772      }
773  
774 <    class SmallRunnable extends CheckedRunnable {
775 <        void realRun() throws Throwable {
774 >    public class SmallRunnable extends CheckedRunnable {
775 >        protected void realRun() throws Throwable {
776              Thread.sleep(SMALL_DELAY_MS);
777          }
778      }
779  
780 <    class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
781 <        void realRun() {
780 >    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
781 >        protected void realRun() {
782              try {
783                  Thread.sleep(SMALL_DELAY_MS);
784 <            }
504 <            catch (InterruptedException ok) {
505 <            }
784 >            } catch (InterruptedException ok) {}
785          }
786      }
787  
788 <    class SmallCallable extends CheckedCallable {
789 <        Object realCall() throws Throwable {
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 <    class SmallInterruptedRunnable extends CheckedInterruptedRunnable {
796 <        void realRun() throws InterruptedException {
518 <            Thread.sleep(SMALL_DELAY_MS);
519 <        }
520 <    }
521 <
522 <    class MediumRunnable extends CheckedRunnable {
523 <        void realRun() throws Throwable {
795 >    public class MediumRunnable extends CheckedRunnable {
796 >        protected void realRun() throws Throwable {
797              Thread.sleep(MEDIUM_DELAY_MS);
798          }
799      }
800  
801 <    class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
802 <        void realRun() throws InterruptedException {
801 >    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
802 >        protected void realRun() throws InterruptedException {
803              Thread.sleep(MEDIUM_DELAY_MS);
804          }
805      }
806  
807 <    class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
808 <        void realRun() {
807 >    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
808 >        protected void realRun() {
809              try {
810                  Thread.sleep(MEDIUM_DELAY_MS);
811 <            }
539 <            catch (InterruptedException ok) {
540 <            }
811 >            } catch (InterruptedException ok) {}
812          }
813      }
814  
815 <    class LongPossiblyInterruptedRunnable extends CheckedRunnable {
816 <        void realRun() {
815 >    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
816 >        protected void realRun() {
817              try {
818                  Thread.sleep(LONG_DELAY_MS);
819 <            }
549 <            catch (InterruptedException ok) {
550 <            }
819 >            } catch (InterruptedException ok) {}
820          }
821      }
822  
823      /**
824       * For use as ThreadFactory in constructors
825       */
826 <    static class SimpleThreadFactory implements ThreadFactory {
826 >    public static class SimpleThreadFactory implements ThreadFactory {
827          public Thread newThread(Runnable r) {
828              return new Thread(r);
829          }
830      }
831  
832 <    static class TrackedShortRunnable implements Runnable {
833 <        volatile boolean done = false;
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(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) {
570 <            }
865 >            } catch (InterruptedException ok) {}
866          }
867      }
868  
869 <    static class TrackedMediumRunnable implements Runnable {
870 <        volatile boolean done = false;
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                  done = true;
875 <            } catch (InterruptedException ok) {
581 <            }
875 >            } catch (InterruptedException ok) {}
876          }
877      }
878  
879 <    static class TrackedLongRunnable implements Runnable {
880 <        volatile boolean done = false;
879 >    public static class TrackedLongRunnable implements Runnable {
880 >        public volatile boolean done = false;
881          public void run() {
882              try {
883                  Thread.sleep(LONG_DELAY_MS);
884                  done = true;
885 <            } catch (InterruptedException ok) {
592 <            }
885 >            } catch (InterruptedException ok) {}
886          }
887      }
888  
889 <    static class TrackedNoOpRunnable implements Runnable {
890 <        volatile boolean done = false;
889 >    public static class TrackedNoOpRunnable implements Runnable {
890 >        public volatile boolean done = false;
891          public void run() {
892              done = true;
893          }
894      }
895  
896 <    static class TrackedCallable implements Callable {
897 <        volatile boolean done = false;
896 >    public static class TrackedCallable implements Callable {
897 >        public volatile boolean done = false;
898          public Object call() {
899              try {
900                  Thread.sleep(SMALL_DELAY_MS);
901                  done = true;
902 <            } catch (InterruptedException ok) {
610 <            }
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 +        }
936 +    }
937  
938      /**
939       * For use as RejectedExecutionHandler in constructors
940       */
941 <    static class NoOpREHandler implements RejectedExecutionHandler {
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 +
965   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines