ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.78
Committed: Sat May 7 19:03:26 2011 UTC (13 years ago) by jsr166
Branch: MAIN
CVS Tags: release-1_7_0
Changes since 1.77: +14 -0 lines
Log Message:
Improve ReentrantLock and ReentrantReadWriteLock tests

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