ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.81
Committed: Sat May 21 06:24:33 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.80: +53 -16 lines
Log Message:
various test improvements

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