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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines