ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.80
Committed: Fri May 13 21:48:58 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.79: +9 -11 lines
Log Message:
More cross-pollination of RL and RRWL tests; don't rely on thread.join not returning early

File Contents

# User Rev Content
1 dl 1.1 /*
2 dl 1.13 * 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 jsr166 1.74 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.27 * Other contributors include Andrew Wright, Jeffrey Hayes,
6     * Pat Fisher, Mike Judd.
7 dl 1.1 */
8    
9     import junit.framework.*;
10 jsr166 1.79 import java.io.ByteArrayInputStream;
11     import java.io.ByteArrayOutputStream;
12     import java.io.ObjectInputStream;
13     import java.io.ObjectOutputStream;
14 jsr166 1.72 import java.util.Arrays;
15     import java.util.NoSuchElementException;
16 jsr166 1.53 import java.util.PropertyPermission;
17 dl 1.1 import java.util.concurrent.*;
18 jsr166 1.53 import java.util.concurrent.atomic.AtomicReference;
19 jsr166 1.36 import static java.util.concurrent.TimeUnit.MILLISECONDS;
20 jsr166 1.66 import static java.util.concurrent.TimeUnit.NANOSECONDS;
21 jsr166 1.53 import java.security.CodeSource;
22     import java.security.Permission;
23     import java.security.PermissionCollection;
24     import java.security.Permissions;
25     import java.security.Policy;
26     import java.security.ProtectionDomain;
27     import java.security.SecurityPermission;
28 dl 1.1
29     /**
30 dl 1.5 * Base class for JSR166 Junit TCK tests. Defines some constants,
31     * utility methods and classes, as well as a simple framework for
32     * helping to make sure that assertions failing in generated threads
33     * cause the associated test that generated them to itself fail (which
34 jsr166 1.27 * JUnit does not otherwise arrange). The rules for creating such
35 dl 1.5 * tests are:
36 dl 1.1 *
37     * <ol>
38     *
39     * <li> All assertions in code running in generated threads must use
40 jsr166 1.27 * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
41 dl 1.18 * #threadAssertEquals}, or {@link #threadAssertNull}, (not
42 jsr166 1.50 * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
43 dl 1.1 * particularly recommended) for other code to use these forms too.
44     * Only the most typically used JUnit assertion methods are defined
45     * this way, but enough to live with.</li>
46     *
47 dl 1.18 * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
48 jsr166 1.50 * to invoke {@code super.setUp} and {@code super.tearDown} within
49 dl 1.1 * them. These methods are used to clear and check for thread
50     * assertion failures.</li>
51     *
52 jsr166 1.51 * <li>All delays and timeouts must use one of the constants {@code
53 jsr166 1.50 * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
54     * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
55 dl 1.5 * discriminable from zero time, and always allows enough time for the
56     * small amounts of computation (creating a thread, calling a few
57 dl 1.1 * methods, etc) needed to reach a timeout point. Similarly, a SMALL
58     * is always discriminable as larger than SHORT and smaller than
59     * MEDIUM. And so on. These constants are set to conservative values,
60 dl 1.2 * but even so, if there is ever any doubt, they can all be increased
61 jsr166 1.27 * in one spot to rerun tests on slower platforms.</li>
62 dl 1.1 *
63     * <li> All threads generated must be joined inside each test case
64 jsr166 1.50 * method (or {@code fail} to do so) before returning from the
65     * method. The {@code joinPool} method can be used to do this when
66 dl 1.1 * using Executors.</li>
67     *
68     * </ol>
69 dl 1.6 *
70     * <p> <b>Other notes</b>
71     * <ul>
72     *
73     * <li> Usually, there is one testcase method per JSR166 method
74     * covering "normal" operation, and then as many exception-testing
75     * methods as there are exceptions the method can throw. Sometimes
76     * there are multiple tests per JSR166 method when the different
77     * "normal" behaviors differ significantly. And sometimes testcases
78     * cover multiple methods when they cannot be tested in
79     * isolation.</li>
80 jsr166 1.27 *
81 dl 1.6 * <li> The documentation style for testcases is to provide as javadoc
82     * a simple sentence or two describing the property that the testcase
83     * method purports to test. The javadocs do not say anything about how
84     * the property is tested. To find out, read the code.</li>
85     *
86     * <li> These tests are "conformance tests", and do not attempt to
87     * test throughput, latency, scalability or other performance factors
88     * (see the separate "jtreg" tests for a set intended to check these
89     * for the most central aspects of functionality.) So, most tests use
90     * the smallest sensible numbers of threads, collection sizes, etc
91     * needed to check basic conformance.</li>
92     *
93     * <li>The test classes currently do not declare inclusion in
94     * any particular package to simplify things for people integrating
95     * them in TCK test suites.</li>
96     *
97 jsr166 1.50 * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
98 dl 1.6 * runs all JSR166 unit tests.</li>
99     *
100     * </ul>
101 dl 1.1 */
102     public class JSR166TestCase extends TestCase {
103 jsr166 1.49 private static final boolean useSecurityManager =
104     Boolean.getBoolean("jsr166.useSecurityManager");
105    
106 jsr166 1.62 protected static final boolean expensiveTests =
107     Boolean.getBoolean("jsr166.expensiveTests");
108    
109 dl 1.6 /**
110 jsr166 1.61 * If true, report on stdout all "slow" tests, that is, ones that
111     * take more than profileThreshold milliseconds to execute.
112     */
113     private static final boolean profileTests =
114     Boolean.getBoolean("jsr166.profileTests");
115    
116     /**
117     * The number of milliseconds that tests are permitted for
118     * execution without being reported, when profileTests is set.
119     */
120     private static final long profileThreshold =
121     Long.getLong("jsr166.profileThreshold", 100);
122    
123     protected void runTest() throws Throwable {
124     if (profileTests)
125     runTestProfiled();
126     else
127     super.runTest();
128     }
129    
130     protected void runTestProfiled() throws Throwable {
131     long t0 = System.nanoTime();
132     try {
133     super.runTest();
134     } finally {
135     long elapsedMillis =
136     (System.nanoTime() - t0) / (1000L * 1000L);
137     if (elapsedMillis >= profileThreshold)
138     System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
139     }
140     }
141 jsr166 1.63
142 jsr166 1.61 /**
143 dl 1.6 * Runs all JSR166 unit tests using junit.textui.TestRunner
144 jsr166 1.27 */
145 jsr166 1.41 public static void main(String[] args) {
146 jsr166 1.49 if (useSecurityManager) {
147     System.err.println("Setting a permissive security manager");
148     Policy.setPolicy(permissivePolicy());
149     System.setSecurityManager(new SecurityManager());
150     }
151 jsr166 1.56 int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
152    
153 dl 1.16 Test s = suite();
154 dl 1.22 for (int i = 0; i < iters; ++i) {
155 jsr166 1.41 junit.textui.TestRunner.run(s);
156 dl 1.22 System.gc();
157     System.runFinalization();
158     }
159     System.exit(0);
160 dl 1.6 }
161    
162 jsr166 1.60 public static TestSuite newTestSuite(Object... suiteOrClasses) {
163     TestSuite suite = new TestSuite();
164     for (Object suiteOrClass : suiteOrClasses) {
165     if (suiteOrClass instanceof TestSuite)
166     suite.addTest((TestSuite) suiteOrClass);
167     else if (suiteOrClass instanceof Class)
168     suite.addTest(new TestSuite((Class<?>) suiteOrClass));
169     else
170     throw new ClassCastException("not a test suite or class");
171     }
172     return suite;
173     }
174    
175 dl 1.6 /**
176 jsr166 1.60 * Collects all JSR166 unit tests as one suite.
177 jsr166 1.27 */
178 jsr166 1.41 public static Test suite() {
179 jsr166 1.60 return newTestSuite(
180     ForkJoinPoolTest.suite(),
181     ForkJoinTaskTest.suite(),
182     RecursiveActionTest.suite(),
183     RecursiveTaskTest.suite(),
184     LinkedTransferQueueTest.suite(),
185     PhaserTest.suite(),
186     ThreadLocalRandomTest.suite(),
187     AbstractExecutorServiceTest.suite(),
188     AbstractQueueTest.suite(),
189     AbstractQueuedSynchronizerTest.suite(),
190     AbstractQueuedLongSynchronizerTest.suite(),
191     ArrayBlockingQueueTest.suite(),
192     ArrayDequeTest.suite(),
193     AtomicBooleanTest.suite(),
194     AtomicIntegerArrayTest.suite(),
195     AtomicIntegerFieldUpdaterTest.suite(),
196     AtomicIntegerTest.suite(),
197     AtomicLongArrayTest.suite(),
198     AtomicLongFieldUpdaterTest.suite(),
199     AtomicLongTest.suite(),
200     AtomicMarkableReferenceTest.suite(),
201     AtomicReferenceArrayTest.suite(),
202     AtomicReferenceFieldUpdaterTest.suite(),
203     AtomicReferenceTest.suite(),
204     AtomicStampedReferenceTest.suite(),
205     ConcurrentHashMapTest.suite(),
206     ConcurrentLinkedDequeTest.suite(),
207     ConcurrentLinkedQueueTest.suite(),
208     ConcurrentSkipListMapTest.suite(),
209     ConcurrentSkipListSubMapTest.suite(),
210     ConcurrentSkipListSetTest.suite(),
211     ConcurrentSkipListSubSetTest.suite(),
212     CopyOnWriteArrayListTest.suite(),
213     CopyOnWriteArraySetTest.suite(),
214     CountDownLatchTest.suite(),
215     CyclicBarrierTest.suite(),
216     DelayQueueTest.suite(),
217     EntryTest.suite(),
218     ExchangerTest.suite(),
219     ExecutorsTest.suite(),
220     ExecutorCompletionServiceTest.suite(),
221     FutureTaskTest.suite(),
222     LinkedBlockingDequeTest.suite(),
223     LinkedBlockingQueueTest.suite(),
224     LinkedListTest.suite(),
225     LockSupportTest.suite(),
226     PriorityBlockingQueueTest.suite(),
227     PriorityQueueTest.suite(),
228     ReentrantLockTest.suite(),
229     ReentrantReadWriteLockTest.suite(),
230     ScheduledExecutorTest.suite(),
231     ScheduledExecutorSubclassTest.suite(),
232     SemaphoreTest.suite(),
233     SynchronousQueueTest.suite(),
234     SystemTest.suite(),
235     ThreadLocalTest.suite(),
236     ThreadPoolExecutorTest.suite(),
237     ThreadPoolExecutorSubclassTest.suite(),
238     ThreadTest.suite(),
239     TimeUnitTest.suite(),
240     TreeMapTest.suite(),
241     TreeSetTest.suite(),
242     TreeSubMapTest.suite(),
243     TreeSubSetTest.suite());
244 dl 1.6 }
245    
246 dl 1.1
247 dl 1.2 public static long SHORT_DELAY_MS;
248     public static long SMALL_DELAY_MS;
249     public static long MEDIUM_DELAY_MS;
250     public static long LONG_DELAY_MS;
251    
252    
253     /**
254 jsr166 1.27 * Returns the shortest timed delay. This could
255 dl 1.15 * be reimplemented to use for example a Property.
256 jsr166 1.27 */
257 dl 1.2 protected long getShortDelay() {
258 dl 1.21 return 50;
259 dl 1.2 }
260    
261    
262     /**
263 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
264 dl 1.2 */
265 jsr166 1.43 protected void setDelays() {
266 dl 1.2 SHORT_DELAY_MS = getShortDelay();
267 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
268 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
269 jsr166 1.71 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
270 dl 1.2 }
271    
272 dl 1.1 /**
273 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
274 dl 1.1 */
275 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
276     = new AtomicReference<Throwable>(null);
277 dl 1.1
278     /**
279 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
280     * harness thread, triggering a test case failure. Only the first
281     * failure is recorded; subsequent calls to this method from within
282     * the same test have no effect.
283 dl 1.1 */
284 jsr166 1.53 public void threadRecordFailure(Throwable t) {
285     threadFailure.compareAndSet(null, t);
286     }
287    
288 jsr166 1.27 public void setUp() {
289 dl 1.2 setDelays();
290 dl 1.1 }
291    
292     /**
293 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
294     * by rethrowing, in the test harness thread, any exception recorded
295     * earlier by threadRecordFailure.
296     */
297     public void tearDown() throws Exception {
298 jsr166 1.70 Throwable t = threadFailure.getAndSet(null);
299 jsr166 1.53 if (t != null) {
300     if (t instanceof Error)
301     throw (Error) t;
302     else if (t instanceof RuntimeException)
303     throw (RuntimeException) t;
304     else if (t instanceof Exception)
305     throw (Exception) t;
306 jsr166 1.57 else {
307     AssertionFailedError afe =
308     new AssertionFailedError(t.toString());
309     afe.initCause(t);
310     throw afe;
311     }
312 jsr166 1.53 }
313 dl 1.1 }
314    
315 dl 1.5 /**
316 jsr166 1.53 * Just like fail(reason), but additionally recording (using
317 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
318     * the current testcase will fail.
319 jsr166 1.27 */
320 dl 1.1 public void threadFail(String reason) {
321 jsr166 1.53 try {
322     fail(reason);
323 jsr166 1.57 } catch (AssertionFailedError t) {
324 jsr166 1.53 threadRecordFailure(t);
325     fail(reason);
326     }
327 dl 1.1 }
328    
329 dl 1.5 /**
330 jsr166 1.53 * Just like assertTrue(b), but additionally recording (using
331 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
332     * the current testcase will fail.
333 jsr166 1.27 */
334 dl 1.1 public void threadAssertTrue(boolean b) {
335 jsr166 1.53 try {
336 dl 1.1 assertTrue(b);
337 jsr166 1.57 } catch (AssertionFailedError t) {
338 jsr166 1.53 threadRecordFailure(t);
339     throw t;
340 dl 1.1 }
341     }
342 dl 1.5
343     /**
344 jsr166 1.53 * Just like assertFalse(b), but additionally recording (using
345 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
346     * the current testcase will fail.
347 jsr166 1.27 */
348 dl 1.1 public void threadAssertFalse(boolean b) {
349 jsr166 1.53 try {
350 dl 1.1 assertFalse(b);
351 jsr166 1.57 } catch (AssertionFailedError t) {
352 jsr166 1.53 threadRecordFailure(t);
353     throw t;
354 dl 1.1 }
355     }
356 dl 1.5
357     /**
358 jsr166 1.53 * Just like assertNull(x), but additionally recording (using
359 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
360     * the current testcase will fail.
361 jsr166 1.27 */
362 dl 1.1 public void threadAssertNull(Object x) {
363 jsr166 1.53 try {
364 dl 1.1 assertNull(x);
365 jsr166 1.57 } catch (AssertionFailedError t) {
366 jsr166 1.53 threadRecordFailure(t);
367     throw t;
368 dl 1.1 }
369     }
370 dl 1.5
371     /**
372 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
373 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
374     * the current testcase will fail.
375 jsr166 1.27 */
376 dl 1.1 public void threadAssertEquals(long x, long y) {
377 jsr166 1.53 try {
378 dl 1.1 assertEquals(x, y);
379 jsr166 1.57 } catch (AssertionFailedError t) {
380 jsr166 1.53 threadRecordFailure(t);
381     throw t;
382 dl 1.1 }
383     }
384 dl 1.5
385     /**
386 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
387 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
388     * the current testcase will fail.
389 jsr166 1.27 */
390 dl 1.1 public void threadAssertEquals(Object x, Object y) {
391 jsr166 1.53 try {
392 dl 1.1 assertEquals(x, y);
393 jsr166 1.57 } catch (AssertionFailedError t) {
394 jsr166 1.53 threadRecordFailure(t);
395     throw t;
396 jsr166 1.57 } catch (Throwable t) {
397     threadUnexpectedException(t);
398 dl 1.1 }
399     }
400    
401 dl 1.5 /**
402 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
403 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
404     * the current testcase will fail.
405 jsr166 1.52 */
406     public void threadAssertSame(Object x, Object y) {
407 jsr166 1.53 try {
408 jsr166 1.52 assertSame(x, y);
409 jsr166 1.57 } catch (AssertionFailedError t) {
410 jsr166 1.53 threadRecordFailure(t);
411     throw t;
412 jsr166 1.52 }
413     }
414    
415     /**
416 jsr166 1.53 * Calls threadFail with message "should throw exception".
417 jsr166 1.33 */
418 dl 1.3 public void threadShouldThrow() {
419 jsr166 1.53 threadFail("should throw exception");
420 dl 1.3 }
421    
422 dl 1.5 /**
423 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
424 jsr166 1.40 */
425     public void threadShouldThrow(String exceptionName) {
426 jsr166 1.53 threadFail("should throw " + exceptionName);
427 dl 1.3 }
428    
429 dl 1.31 /**
430 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
431     * then rethrows the exception, wrapping it in an
432     * AssertionFailedError if necessary.
433 dl 1.31 */
434 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
435     threadRecordFailure(t);
436     t.printStackTrace();
437     if (t instanceof RuntimeException)
438     throw (RuntimeException) t;
439     else if (t instanceof Error)
440     throw (Error) t;
441     else {
442 jsr166 1.57 AssertionFailedError afe =
443     new AssertionFailedError("unexpected exception: " + t);
444 jsr166 1.53 t.initCause(t);
445 jsr166 1.57 throw afe;
446 jsr166 1.55 }
447 dl 1.31 }
448 dl 1.3
449 dl 1.1 /**
450 dl 1.76 * Delays, via Thread.sleep for the given millisecond delay, but
451     * if the sleep is shorter than specified, may re-sleep or yield
452     * until time elapses.
453     */
454 jsr166 1.80 public static void delay(long millis) throws InterruptedException {
455 dl 1.76 long startTime = System.nanoTime();
456 jsr166 1.80 long ns = millis * 1000 * 1000;
457 dl 1.76 for (;;) {
458 jsr166 1.80 if (millis > 0L)
459     Thread.sleep(millis);
460 dl 1.76 else // too short to sleep
461     Thread.yield();
462     long d = ns - (System.nanoTime() - startTime);
463     if (d > 0L)
464 jsr166 1.80 millis = d / (1000 * 1000);
465 dl 1.76 else
466     break;
467     }
468     }
469    
470     /**
471 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
472 dl 1.1 */
473     public void joinPool(ExecutorService exec) {
474     try {
475     exec.shutdown();
476 jsr166 1.54 assertTrue("ExecutorService did not terminate in a timely manner",
477 jsr166 1.71 exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
478 jsr166 1.33 } catch (SecurityException ok) {
479 dl 1.22 // Allowed in case test doesn't have privs
480 jsr166 1.33 } catch (InterruptedException ie) {
481 jsr166 1.44 fail("Unexpected InterruptedException");
482 dl 1.1 }
483     }
484    
485 jsr166 1.78 /**
486 jsr166 1.80 * Checks that thread does not terminate within the given millisecond delay.
487 jsr166 1.78 */
488 jsr166 1.80 public void assertThreadStaysAlive(Thread thread, long millis) {
489 jsr166 1.78 try {
490 jsr166 1.80 // No need to optimize the failing case via Thread.join.
491     delay(millis);
492 jsr166 1.78 assertTrue(thread.isAlive());
493     } catch (InterruptedException ie) {
494     fail("Unexpected InterruptedException");
495     }
496     }
497 dl 1.5
498     /**
499 jsr166 1.53 * Fails with message "should throw exception".
500 jsr166 1.27 */
501 dl 1.3 public void shouldThrow() {
502     fail("Should throw exception");
503     }
504    
505 dl 1.5 /**
506 jsr166 1.53 * Fails with message "should throw " + exceptionName.
507 jsr166 1.40 */
508     public void shouldThrow(String exceptionName) {
509     fail("Should throw " + exceptionName);
510     }
511    
512     /**
513 dl 1.1 * The number of elements to place in collections, arrays, etc.
514     */
515 jsr166 1.45 public static final int SIZE = 20;
516 dl 1.1
517     // Some convenient Integer constants
518    
519 jsr166 1.47 public static final Integer zero = new Integer(0);
520     public static final Integer one = new Integer(1);
521     public static final Integer two = new Integer(2);
522     public static final Integer three = new Integer(3);
523 jsr166 1.45 public static final Integer four = new Integer(4);
524     public static final Integer five = new Integer(5);
525 jsr166 1.47 public static final Integer six = new Integer(6);
526 jsr166 1.45 public static final Integer seven = new Integer(7);
527     public static final Integer eight = new Integer(8);
528 jsr166 1.47 public static final Integer nine = new Integer(9);
529 jsr166 1.45 public static final Integer m1 = new Integer(-1);
530     public static final Integer m2 = new Integer(-2);
531     public static final Integer m3 = new Integer(-3);
532 jsr166 1.47 public static final Integer m4 = new Integer(-4);
533     public static final Integer m5 = new Integer(-5);
534     public static final Integer m6 = new Integer(-6);
535 jsr166 1.45 public static final Integer m10 = new Integer(-10);
536 dl 1.7
537    
538     /**
539 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
540     * the specified permissions. If there is no current security
541     * manager, the runnable is run twice, both with and without a
542     * security manager. We require that any security manager permit
543     * getPolicy/setPolicy.
544     */
545     public void runWithPermissions(Runnable r, Permission... permissions) {
546     SecurityManager sm = System.getSecurityManager();
547     if (sm == null) {
548     r.run();
549     Policy savedPolicy = Policy.getPolicy();
550     try {
551     Policy.setPolicy(permissivePolicy());
552     System.setSecurityManager(new SecurityManager());
553     runWithPermissions(r, permissions);
554     } finally {
555     System.setSecurityManager(null);
556     Policy.setPolicy(savedPolicy);
557     }
558     } else {
559     Policy savedPolicy = Policy.getPolicy();
560     AdjustablePolicy policy = new AdjustablePolicy(permissions);
561     Policy.setPolicy(policy);
562    
563     try {
564     r.run();
565     } finally {
566     policy.addPermission(new SecurityPermission("setPolicy"));
567     Policy.setPolicy(savedPolicy);
568     }
569     }
570     }
571    
572     /**
573     * Runs a runnable without any permissions.
574     */
575     public void runWithoutPermissions(Runnable r) {
576     runWithPermissions(r);
577     }
578    
579     /**
580 dl 1.7 * A security policy where new permissions can be dynamically added
581     * or all cleared.
582     */
583 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
584 dl 1.7 Permissions perms = new Permissions();
585 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
586     for (Permission permission : permissions)
587     perms.add(permission);
588     }
589 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
590     void clearPermissions() { perms = new Permissions(); }
591 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
592     return perms;
593     }
594     public PermissionCollection getPermissions(ProtectionDomain pd) {
595     return perms;
596     }
597     public boolean implies(ProtectionDomain pd, Permission p) {
598     return perms.implies(p);
599     }
600     public void refresh() {}
601 dl 1.7 }
602 dl 1.1
603 jsr166 1.38 /**
604 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
605     */
606     public static Policy permissivePolicy() {
607     return new AdjustablePolicy
608     // Permissions j.u.c. needs directly
609     (new RuntimePermission("modifyThread"),
610     new RuntimePermission("getClassLoader"),
611     new RuntimePermission("setContextClassLoader"),
612     // Permissions needed to change permissions!
613     new SecurityPermission("getPolicy"),
614     new SecurityPermission("setPolicy"),
615     new RuntimePermission("setSecurityManager"),
616     // Permissions needed by the junit test harness
617     new RuntimePermission("accessDeclaredMembers"),
618     new PropertyPermission("*", "read"),
619     new java.io.FilePermission("<<ALL FILES>>", "read"));
620     }
621    
622     /**
623 jsr166 1.60 * Sleeps until the given time has elapsed.
624     * Throws AssertionFailedError if interrupted.
625     */
626     void sleep(long millis) {
627     try {
628 dl 1.76 delay(millis);
629 jsr166 1.60 } catch (InterruptedException ie) {
630     AssertionFailedError afe =
631     new AssertionFailedError("Unexpected InterruptedException");
632     afe.initCause(ie);
633     throw afe;
634     }
635     }
636    
637     /**
638 jsr166 1.59 * Sleeps until the timeout has elapsed, or interrupted.
639 jsr166 1.38 * Does <em>NOT</em> throw InterruptedException.
640     */
641     void sleepTillInterrupted(long timeoutMillis) {
642     try {
643     Thread.sleep(timeoutMillis);
644 jsr166 1.44 } catch (InterruptedException wakeup) {}
645 jsr166 1.38 }
646    
647     /**
648 jsr166 1.65 * Waits up to the specified number of milliseconds for the given
649     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
650     */
651     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
652     long timeoutNanos = timeoutMillis * 1000L * 1000L;
653     long t0 = System.nanoTime();
654     for (;;) {
655     Thread.State s = thread.getState();
656     if (s == Thread.State.BLOCKED ||
657     s == Thread.State.WAITING ||
658 jsr166 1.67 s == Thread.State.TIMED_WAITING)
659 jsr166 1.65 return;
660 jsr166 1.67 else if (s == Thread.State.TERMINATED)
661     fail("Unexpected thread termination");
662     else if (System.nanoTime() - t0 > timeoutNanos) {
663     threadAssertTrue(thread.isAlive());
664     return;
665     }
666 jsr166 1.65 Thread.yield();
667     }
668     }
669    
670     /**
671 jsr166 1.75 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
672     * state: BLOCKED, WAITING, or TIMED_WAITING.
673     */
674     void waitForThreadToEnterWaitState(Thread thread) {
675     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
676     }
677    
678     /**
679 jsr166 1.66 * Returns the number of milliseconds since time given by
680     * startNanoTime, which must have been previously returned from a
681     * call to {@link System.nanoTime()}.
682     */
683     long millisElapsedSince(long startNanoTime) {
684     return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
685     }
686 jsr166 1.68
687 jsr166 1.66 /**
688 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
689 jsr166 1.38 */
690     Thread newStartedThread(Runnable runnable) {
691     Thread t = new Thread(runnable);
692 jsr166 1.58 t.setDaemon(true);
693 jsr166 1.38 t.start();
694     return t;
695     }
696 dl 1.1
697 jsr166 1.59 /**
698     * Waits for the specified time (in milliseconds) for the thread
699     * to terminate (using {@link Thread#join(long)}), else interrupts
700     * the thread (in the hope that it may terminate later) and fails.
701     */
702     void awaitTermination(Thread t, long timeoutMillis) {
703     try {
704     t.join(timeoutMillis);
705     } catch (InterruptedException ie) {
706     threadUnexpectedException(ie);
707     } finally {
708     if (t.isAlive()) {
709     t.interrupt();
710     fail("Test timed out");
711     }
712     }
713     }
714    
715 jsr166 1.75 /**
716     * Waits for LONG_DELAY_MS milliseconds for the thread to
717     * terminate (using {@link Thread#join(long)}), else interrupts
718     * the thread (in the hope that it may terminate later) and fails.
719     */
720     void awaitTermination(Thread t) {
721     awaitTermination(t, LONG_DELAY_MS);
722     }
723    
724 dl 1.1 // Some convenient Runnable classes
725    
726 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
727     protected abstract void realRun() throws Throwable;
728 jsr166 1.35
729     public final void run() {
730     try {
731     realRun();
732     } catch (Throwable t) {
733     threadUnexpectedException(t);
734     }
735     }
736     }
737    
738 jsr166 1.45 public abstract class RunnableShouldThrow implements Runnable {
739     protected abstract void realRun() throws Throwable;
740 jsr166 1.40
741     final Class<?> exceptionClass;
742    
743     <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
744     this.exceptionClass = exceptionClass;
745     }
746    
747     public final void run() {
748     try {
749     realRun();
750     threadShouldThrow(exceptionClass.getSimpleName());
751     } catch (Throwable t) {
752     if (! exceptionClass.isInstance(t))
753     threadUnexpectedException(t);
754     }
755     }
756     }
757    
758 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
759     protected abstract void realRun() throws Throwable;
760 jsr166 1.40
761     final Class<?> exceptionClass;
762    
763     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
764     this.exceptionClass = exceptionClass;
765     }
766    
767     public final void run() {
768     try {
769     realRun();
770     threadShouldThrow(exceptionClass.getSimpleName());
771     } catch (Throwable t) {
772     if (! exceptionClass.isInstance(t))
773     threadUnexpectedException(t);
774     }
775     }
776     }
777    
778 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
779     protected abstract void realRun() throws Throwable;
780 jsr166 1.35
781     public final void run() {
782     try {
783     realRun();
784 jsr166 1.40 threadShouldThrow("InterruptedException");
785 jsr166 1.35 } catch (InterruptedException success) {
786     } catch (Throwable t) {
787     threadUnexpectedException(t);
788     }
789     }
790     }
791    
792 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
793     protected abstract T realCall() throws Throwable;
794 jsr166 1.35
795     public final T call() {
796     try {
797     return realCall();
798     } catch (Throwable t) {
799     threadUnexpectedException(t);
800 jsr166 1.53 return null;
801 jsr166 1.35 }
802 jsr166 1.40 }
803     }
804    
805 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
806     implements Callable<T> {
807 jsr166 1.45 protected abstract T realCall() throws Throwable;
808 jsr166 1.40
809     public final T call() {
810     try {
811     T result = realCall();
812     threadShouldThrow("InterruptedException");
813     return result;
814     } catch (InterruptedException success) {
815     } catch (Throwable t) {
816     threadUnexpectedException(t);
817     }
818     return null;
819 jsr166 1.35 }
820     }
821    
822 jsr166 1.45 public static class NoOpRunnable implements Runnable {
823 dl 1.1 public void run() {}
824     }
825    
826 jsr166 1.45 public static class NoOpCallable implements Callable {
827 dl 1.1 public Object call() { return Boolean.TRUE; }
828 dl 1.10 }
829    
830 jsr166 1.45 public static final String TEST_STRING = "a test string";
831 dl 1.10
832 jsr166 1.45 public static class StringTask implements Callable<String> {
833 dl 1.10 public String call() { return TEST_STRING; }
834     }
835    
836 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
837     return new CheckedCallable<String>() {
838 jsr166 1.64 protected String realCall() {
839 jsr166 1.48 try {
840     latch.await();
841     } catch (InterruptedException quittingTime) {}
842     return TEST_STRING;
843     }};
844     }
845    
846 jsr166 1.73 public Runnable awaiter(final CountDownLatch latch) {
847     return new CheckedRunnable() {
848     public void realRun() throws InterruptedException {
849 jsr166 1.79 await(latch);
850 jsr166 1.73 }};
851     }
852    
853 jsr166 1.79 public void await(CountDownLatch latch) {
854     try {
855     assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
856     } catch (Throwable t) {
857     threadUnexpectedException(t);
858     }
859     }
860    
861 jsr166 1.45 public static class NPETask implements Callable<String> {
862 dl 1.10 public String call() { throw new NullPointerException(); }
863     }
864    
865 jsr166 1.45 public static class CallableOne implements Callable<Integer> {
866 dl 1.10 public Integer call() { return one; }
867 dl 1.1 }
868    
869 jsr166 1.45 public class ShortRunnable extends CheckedRunnable {
870     protected void realRun() throws Throwable {
871 dl 1.76 delay(SHORT_DELAY_MS);
872 dl 1.1 }
873     }
874    
875 jsr166 1.45 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
876     protected void realRun() throws InterruptedException {
877 dl 1.76 delay(SHORT_DELAY_MS);
878 dl 1.1 }
879     }
880    
881 jsr166 1.45 public class SmallRunnable extends CheckedRunnable {
882     protected void realRun() throws Throwable {
883 dl 1.76 delay(SMALL_DELAY_MS);
884 dl 1.1 }
885     }
886    
887 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
888     protected void realRun() {
889 dl 1.6 try {
890 dl 1.76 delay(SMALL_DELAY_MS);
891 jsr166 1.44 } catch (InterruptedException ok) {}
892 dl 1.6 }
893     }
894    
895 jsr166 1.45 public class SmallCallable extends CheckedCallable {
896     protected Object realCall() throws InterruptedException {
897 dl 1.76 delay(SMALL_DELAY_MS);
898 dl 1.1 return Boolean.TRUE;
899     }
900     }
901    
902 jsr166 1.45 public class MediumRunnable extends CheckedRunnable {
903     protected void realRun() throws Throwable {
904 dl 1.76 delay(MEDIUM_DELAY_MS);
905 dl 1.1 }
906     }
907    
908 jsr166 1.45 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
909     protected void realRun() throws InterruptedException {
910 dl 1.76 delay(MEDIUM_DELAY_MS);
911 dl 1.1 }
912     }
913    
914 jsr166 1.63 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
915     return new CheckedRunnable() {
916     protected void realRun() {
917     try {
918 dl 1.76 delay(timeoutMillis);
919 jsr166 1.63 } catch (InterruptedException ok) {}
920     }};
921     }
922    
923 jsr166 1.45 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
924     protected void realRun() {
925 dl 1.1 try {
926 dl 1.76 delay(MEDIUM_DELAY_MS);
927 jsr166 1.44 } catch (InterruptedException ok) {}
928 dl 1.1 }
929     }
930 dl 1.5
931 jsr166 1.45 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
932     protected void realRun() {
933 dl 1.12 try {
934 dl 1.76 delay(LONG_DELAY_MS);
935 jsr166 1.44 } catch (InterruptedException ok) {}
936 dl 1.12 }
937     }
938    
939 dl 1.5 /**
940     * For use as ThreadFactory in constructors
941     */
942 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
943 jsr166 1.33 public Thread newThread(Runnable r) {
944 dl 1.5 return new Thread(r);
945 jsr166 1.27 }
946 dl 1.5 }
947    
948 jsr166 1.61 public interface TrackedRunnable extends Runnable {
949     boolean isDone();
950     }
951    
952     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
953     return new TrackedRunnable() {
954     private volatile boolean done = false;
955     public boolean isDone() { return done; }
956     public void run() {
957     try {
958 dl 1.76 delay(timeoutMillis);
959 jsr166 1.61 done = true;
960     } catch (InterruptedException ok) {}
961     }
962     };
963     }
964    
965 jsr166 1.45 public static class TrackedShortRunnable implements Runnable {
966     public volatile boolean done = false;
967 dl 1.5 public void run() {
968     try {
969 dl 1.76 delay(SHORT_DELAY_MS);
970 jsr166 1.61 done = true;
971     } catch (InterruptedException ok) {}
972     }
973     }
974    
975     public static class TrackedSmallRunnable implements Runnable {
976     public volatile boolean done = false;
977     public void run() {
978     try {
979 dl 1.76 delay(SMALL_DELAY_MS);
980 dl 1.5 done = true;
981 jsr166 1.44 } catch (InterruptedException ok) {}
982 dl 1.6 }
983     }
984    
985 jsr166 1.45 public static class TrackedMediumRunnable implements Runnable {
986     public volatile boolean done = false;
987 dl 1.6 public void run() {
988     try {
989 dl 1.76 delay(MEDIUM_DELAY_MS);
990 dl 1.6 done = true;
991 jsr166 1.44 } catch (InterruptedException ok) {}
992 dl 1.6 }
993     }
994    
995 jsr166 1.45 public static class TrackedLongRunnable implements Runnable {
996     public volatile boolean done = false;
997 dl 1.6 public void run() {
998     try {
999 dl 1.76 delay(LONG_DELAY_MS);
1000 dl 1.6 done = true;
1001 jsr166 1.44 } catch (InterruptedException ok) {}
1002 dl 1.6 }
1003     }
1004    
1005 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
1006     public volatile boolean done = false;
1007 dl 1.6 public void run() {
1008     done = true;
1009 dl 1.5 }
1010     }
1011    
1012 jsr166 1.45 public static class TrackedCallable implements Callable {
1013     public volatile boolean done = false;
1014 dl 1.5 public Object call() {
1015     try {
1016 dl 1.76 delay(SMALL_DELAY_MS);
1017 dl 1.5 done = true;
1018 jsr166 1.44 } catch (InterruptedException ok) {}
1019 dl 1.5 return Boolean.TRUE;
1020     }
1021     }
1022 dl 1.14
1023 jsr166 1.53 /**
1024     * Analog of CheckedRunnable for RecursiveAction
1025     */
1026     public abstract class CheckedRecursiveAction extends RecursiveAction {
1027     protected abstract void realCompute() throws Throwable;
1028    
1029     public final void compute() {
1030     try {
1031     realCompute();
1032     } catch (Throwable t) {
1033     threadUnexpectedException(t);
1034     }
1035     }
1036     }
1037    
1038     /**
1039     * Analog of CheckedCallable for RecursiveTask
1040     */
1041     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1042     protected abstract T realCompute() throws Throwable;
1043    
1044     public final T compute() {
1045     try {
1046     return realCompute();
1047     } catch (Throwable t) {
1048     threadUnexpectedException(t);
1049     return null;
1050     }
1051     }
1052     }
1053 dl 1.5
1054     /**
1055     * For use as RejectedExecutionHandler in constructors
1056     */
1057 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
1058 jsr166 1.35 public void rejectedExecution(Runnable r,
1059     ThreadPoolExecutor executor) {}
1060 dl 1.5 }
1061 jsr166 1.27
1062 jsr166 1.60 /**
1063     * A CyclicBarrier that fails with AssertionFailedErrors instead
1064     * of throwing checked exceptions.
1065     */
1066     public class CheckedBarrier extends CyclicBarrier {
1067     public CheckedBarrier(int parties) { super(parties); }
1068    
1069     public int await() {
1070     try {
1071     return super.await();
1072     } catch (Exception e) {
1073     AssertionFailedError afe =
1074     new AssertionFailedError("Unexpected exception: " + e);
1075     afe.initCause(e);
1076     throw afe;
1077     }
1078     }
1079     }
1080    
1081 jsr166 1.72 public void checkEmpty(BlockingQueue q) {
1082     try {
1083     assertTrue(q.isEmpty());
1084     assertEquals(0, q.size());
1085     assertNull(q.peek());
1086     assertNull(q.poll());
1087     assertNull(q.poll(0, MILLISECONDS));
1088     assertEquals(q.toString(), "[]");
1089     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1090     assertFalse(q.iterator().hasNext());
1091     try {
1092     q.element();
1093     shouldThrow();
1094     } catch (NoSuchElementException success) {}
1095     try {
1096     q.iterator().next();
1097     shouldThrow();
1098     } catch (NoSuchElementException success) {}
1099     try {
1100     q.remove();
1101     shouldThrow();
1102     } catch (NoSuchElementException success) {}
1103     } catch (InterruptedException ie) {
1104     threadUnexpectedException(ie);
1105     }
1106     }
1107    
1108 jsr166 1.79 @SuppressWarnings("unchecked")
1109     public <T> T serialClone(T o) {
1110     try {
1111     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1112     ObjectOutputStream oos = new ObjectOutputStream(bos);
1113     oos.writeObject(o);
1114     oos.flush();
1115     oos.close();
1116     ByteArrayInputStream bin =
1117     new ByteArrayInputStream(bos.toByteArray());
1118     ObjectInputStream ois = new ObjectInputStream(bin);
1119     return (T) ois.readObject();
1120     } catch (Throwable t) {
1121     threadUnexpectedException(t);
1122     return null;
1123     }
1124     }
1125 dl 1.1 }