ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.89
Committed: Fri Jun 3 05:07:14 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.88: +8 -0 lines
Log Message:
improve "uninterruptible" 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.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 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
265 dl 1.2 */
266 jsr166 1.43 protected void setDelays() {
267 dl 1.2 SHORT_DELAY_MS = getShortDelay();
268 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
269 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
270 jsr166 1.71 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
271 dl 1.2 }
272    
273 dl 1.1 /**
274 jsr166 1.81 * Returns a timeout in milliseconds to be used in tests that
275     * verify that operations block or time out.
276     */
277     long timeoutMillis() {
278     return SHORT_DELAY_MS / 4;
279     }
280    
281     /**
282     * Returns a new Date instance representing a time delayMillis
283     * milliseconds in the future.
284     */
285     Date delayedDate(long delayMillis) {
286 jsr166 1.84 return new Date(System.currentTimeMillis() + delayMillis);
287 jsr166 1.81 }
288    
289     /**
290 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
291 dl 1.1 */
292 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
293     = new AtomicReference<Throwable>(null);
294 dl 1.1
295     /**
296 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
297     * harness thread, triggering a test case failure. Only the first
298     * failure is recorded; subsequent calls to this method from within
299     * the same test have no effect.
300 dl 1.1 */
301 jsr166 1.53 public void threadRecordFailure(Throwable t) {
302     threadFailure.compareAndSet(null, t);
303     }
304    
305 jsr166 1.27 public void setUp() {
306 dl 1.2 setDelays();
307 dl 1.1 }
308    
309     /**
310 jsr166 1.85 * Extra checks that get done for all test cases.
311     *
312 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
313     * by rethrowing, in the test harness thread, any exception recorded
314     * earlier by threadRecordFailure.
315 jsr166 1.85 *
316     * Triggers test case failure if interrupt status is set in the main thread.
317 jsr166 1.53 */
318     public void tearDown() throws Exception {
319 jsr166 1.70 Throwable t = threadFailure.getAndSet(null);
320 jsr166 1.53 if (t != null) {
321     if (t instanceof Error)
322     throw (Error) t;
323     else if (t instanceof RuntimeException)
324     throw (RuntimeException) t;
325     else if (t instanceof Exception)
326     throw (Exception) t;
327 jsr166 1.57 else {
328     AssertionFailedError afe =
329     new AssertionFailedError(t.toString());
330     afe.initCause(t);
331     throw afe;
332     }
333 jsr166 1.53 }
334 jsr166 1.85
335     if (Thread.interrupted())
336     throw new AssertionFailedError("interrupt status set in main thread");
337 dl 1.1 }
338    
339 dl 1.5 /**
340 jsr166 1.53 * Just like fail(reason), 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 threadFail(String reason) {
345 jsr166 1.53 try {
346     fail(reason);
347 jsr166 1.57 } catch (AssertionFailedError t) {
348 jsr166 1.53 threadRecordFailure(t);
349     fail(reason);
350     }
351 dl 1.1 }
352    
353 dl 1.5 /**
354 jsr166 1.53 * Just like assertTrue(b), 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 threadAssertTrue(boolean b) {
359 jsr166 1.53 try {
360 dl 1.1 assertTrue(b);
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 assertFalse(b), 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 threadAssertFalse(boolean b) {
373 jsr166 1.53 try {
374 dl 1.1 assertFalse(b);
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 assertNull(x), 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 threadAssertNull(Object x) {
387 jsr166 1.53 try {
388 dl 1.1 assertNull(x);
389 jsr166 1.57 } catch (AssertionFailedError t) {
390 jsr166 1.53 threadRecordFailure(t);
391     throw t;
392 dl 1.1 }
393     }
394 dl 1.5
395     /**
396 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
397 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
398     * the current testcase will fail.
399 jsr166 1.27 */
400 dl 1.1 public void threadAssertEquals(long x, long y) {
401 jsr166 1.53 try {
402 dl 1.1 assertEquals(x, y);
403 jsr166 1.57 } catch (AssertionFailedError t) {
404 jsr166 1.53 threadRecordFailure(t);
405     throw t;
406 dl 1.1 }
407     }
408 dl 1.5
409     /**
410 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
411 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
412     * the current testcase will fail.
413 jsr166 1.27 */
414 dl 1.1 public void threadAssertEquals(Object x, Object y) {
415 jsr166 1.53 try {
416 dl 1.1 assertEquals(x, y);
417 jsr166 1.57 } catch (AssertionFailedError t) {
418 jsr166 1.53 threadRecordFailure(t);
419     throw t;
420 jsr166 1.57 } catch (Throwable t) {
421     threadUnexpectedException(t);
422 dl 1.1 }
423     }
424    
425 dl 1.5 /**
426 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
427 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
428     * the current testcase will fail.
429 jsr166 1.52 */
430     public void threadAssertSame(Object x, Object y) {
431 jsr166 1.53 try {
432 jsr166 1.52 assertSame(x, y);
433 jsr166 1.57 } catch (AssertionFailedError t) {
434 jsr166 1.53 threadRecordFailure(t);
435     throw t;
436 jsr166 1.52 }
437     }
438    
439     /**
440 jsr166 1.53 * Calls threadFail with message "should throw exception".
441 jsr166 1.33 */
442 dl 1.3 public void threadShouldThrow() {
443 jsr166 1.53 threadFail("should throw exception");
444 dl 1.3 }
445    
446 dl 1.5 /**
447 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
448 jsr166 1.40 */
449     public void threadShouldThrow(String exceptionName) {
450 jsr166 1.53 threadFail("should throw " + exceptionName);
451 dl 1.3 }
452    
453 dl 1.31 /**
454 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
455     * then rethrows the exception, wrapping it in an
456     * AssertionFailedError if necessary.
457 dl 1.31 */
458 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
459     threadRecordFailure(t);
460     t.printStackTrace();
461     if (t instanceof RuntimeException)
462     throw (RuntimeException) t;
463     else if (t instanceof Error)
464     throw (Error) t;
465     else {
466 jsr166 1.57 AssertionFailedError afe =
467     new AssertionFailedError("unexpected exception: " + t);
468 jsr166 1.82 afe.initCause(t);
469 jsr166 1.57 throw afe;
470 jsr166 1.55 }
471 dl 1.31 }
472 dl 1.3
473 dl 1.1 /**
474 jsr166 1.81 * Delays, via Thread.sleep, for the given millisecond delay, but
475 dl 1.76 * if the sleep is shorter than specified, may re-sleep or yield
476     * until time elapses.
477     */
478 jsr166 1.81 static void delay(long millis) throws InterruptedException {
479 dl 1.76 long startTime = System.nanoTime();
480 jsr166 1.80 long ns = millis * 1000 * 1000;
481 dl 1.76 for (;;) {
482 jsr166 1.80 if (millis > 0L)
483     Thread.sleep(millis);
484 dl 1.76 else // too short to sleep
485     Thread.yield();
486     long d = ns - (System.nanoTime() - startTime);
487     if (d > 0L)
488 jsr166 1.80 millis = d / (1000 * 1000);
489 dl 1.76 else
490     break;
491     }
492     }
493    
494     /**
495 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
496 dl 1.1 */
497 jsr166 1.81 void joinPool(ExecutorService exec) {
498 dl 1.1 try {
499     exec.shutdown();
500 jsr166 1.54 assertTrue("ExecutorService did not terminate in a timely manner",
501 jsr166 1.71 exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
502 jsr166 1.33 } catch (SecurityException ok) {
503 dl 1.22 // Allowed in case test doesn't have privs
504 jsr166 1.33 } catch (InterruptedException ie) {
505 jsr166 1.44 fail("Unexpected InterruptedException");
506 dl 1.1 }
507     }
508    
509 jsr166 1.78 /**
510 jsr166 1.81 * Checks that thread does not terminate within the default
511     * millisecond delay of {@code timeoutMillis()}.
512     */
513     void assertThreadStaysAlive(Thread thread) {
514     assertThreadStaysAlive(thread, timeoutMillis());
515     }
516    
517     /**
518 jsr166 1.80 * Checks that thread does not terminate within the given millisecond delay.
519 jsr166 1.78 */
520 jsr166 1.81 void assertThreadStaysAlive(Thread thread, long millis) {
521 jsr166 1.78 try {
522 jsr166 1.80 // No need to optimize the failing case via Thread.join.
523     delay(millis);
524 jsr166 1.78 assertTrue(thread.isAlive());
525     } catch (InterruptedException ie) {
526     fail("Unexpected InterruptedException");
527     }
528     }
529 dl 1.5
530     /**
531 jsr166 1.83 * Checks that future.get times out, with the default timeout of
532     * {@code timeoutMillis()}.
533     */
534     void assertFutureTimesOut(Future future) {
535     assertFutureTimesOut(future, timeoutMillis());
536     }
537    
538     /**
539     * Checks that future.get times out, with the given millisecond timeout.
540     */
541     void assertFutureTimesOut(Future future, long timeoutMillis) {
542     long startTime = System.nanoTime();
543     try {
544     future.get(timeoutMillis, MILLISECONDS);
545     shouldThrow();
546     } catch (TimeoutException success) {
547     } catch (Exception e) {
548     threadUnexpectedException(e);
549     } finally { future.cancel(true); }
550     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
551     }
552    
553     /**
554 jsr166 1.53 * Fails with message "should throw exception".
555 jsr166 1.27 */
556 dl 1.3 public void shouldThrow() {
557     fail("Should throw exception");
558     }
559    
560 dl 1.5 /**
561 jsr166 1.53 * Fails with message "should throw " + exceptionName.
562 jsr166 1.40 */
563     public void shouldThrow(String exceptionName) {
564     fail("Should throw " + exceptionName);
565     }
566    
567     /**
568 dl 1.1 * The number of elements to place in collections, arrays, etc.
569     */
570 jsr166 1.45 public static final int SIZE = 20;
571 dl 1.1
572     // Some convenient Integer constants
573    
574 jsr166 1.47 public static final Integer zero = new Integer(0);
575     public static final Integer one = new Integer(1);
576     public static final Integer two = new Integer(2);
577     public static final Integer three = new Integer(3);
578 jsr166 1.45 public static final Integer four = new Integer(4);
579     public static final Integer five = new Integer(5);
580 jsr166 1.47 public static final Integer six = new Integer(6);
581 jsr166 1.45 public static final Integer seven = new Integer(7);
582     public static final Integer eight = new Integer(8);
583 jsr166 1.47 public static final Integer nine = new Integer(9);
584 jsr166 1.45 public static final Integer m1 = new Integer(-1);
585     public static final Integer m2 = new Integer(-2);
586     public static final Integer m3 = new Integer(-3);
587 jsr166 1.47 public static final Integer m4 = new Integer(-4);
588     public static final Integer m5 = new Integer(-5);
589     public static final Integer m6 = new Integer(-6);
590 jsr166 1.45 public static final Integer m10 = new Integer(-10);
591 dl 1.7
592    
593     /**
594 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
595     * the specified permissions. If there is no current security
596     * manager, the runnable is run twice, both with and without a
597     * security manager. We require that any security manager permit
598     * getPolicy/setPolicy.
599     */
600     public void runWithPermissions(Runnable r, Permission... permissions) {
601     SecurityManager sm = System.getSecurityManager();
602     if (sm == null) {
603     r.run();
604     Policy savedPolicy = Policy.getPolicy();
605     try {
606     Policy.setPolicy(permissivePolicy());
607     System.setSecurityManager(new SecurityManager());
608     runWithPermissions(r, permissions);
609     } finally {
610     System.setSecurityManager(null);
611     Policy.setPolicy(savedPolicy);
612     }
613     } else {
614     Policy savedPolicy = Policy.getPolicy();
615     AdjustablePolicy policy = new AdjustablePolicy(permissions);
616     Policy.setPolicy(policy);
617    
618     try {
619     r.run();
620     } finally {
621     policy.addPermission(new SecurityPermission("setPolicy"));
622     Policy.setPolicy(savedPolicy);
623     }
624     }
625     }
626    
627     /**
628     * Runs a runnable without any permissions.
629     */
630     public void runWithoutPermissions(Runnable r) {
631     runWithPermissions(r);
632     }
633    
634     /**
635 dl 1.7 * A security policy where new permissions can be dynamically added
636     * or all cleared.
637     */
638 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
639 dl 1.7 Permissions perms = new Permissions();
640 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
641     for (Permission permission : permissions)
642     perms.add(permission);
643     }
644 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
645     void clearPermissions() { perms = new Permissions(); }
646 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
647     return perms;
648     }
649     public PermissionCollection getPermissions(ProtectionDomain pd) {
650     return perms;
651     }
652     public boolean implies(ProtectionDomain pd, Permission p) {
653     return perms.implies(p);
654     }
655     public void refresh() {}
656 dl 1.7 }
657 dl 1.1
658 jsr166 1.38 /**
659 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
660     */
661     public static Policy permissivePolicy() {
662     return new AdjustablePolicy
663     // Permissions j.u.c. needs directly
664     (new RuntimePermission("modifyThread"),
665     new RuntimePermission("getClassLoader"),
666     new RuntimePermission("setContextClassLoader"),
667     // Permissions needed to change permissions!
668     new SecurityPermission("getPolicy"),
669     new SecurityPermission("setPolicy"),
670     new RuntimePermission("setSecurityManager"),
671     // Permissions needed by the junit test harness
672     new RuntimePermission("accessDeclaredMembers"),
673     new PropertyPermission("*", "read"),
674     new java.io.FilePermission("<<ALL FILES>>", "read"));
675     }
676    
677     /**
678 jsr166 1.60 * Sleeps until the given time has elapsed.
679     * Throws AssertionFailedError if interrupted.
680     */
681     void sleep(long millis) {
682     try {
683 dl 1.76 delay(millis);
684 jsr166 1.60 } catch (InterruptedException ie) {
685     AssertionFailedError afe =
686     new AssertionFailedError("Unexpected InterruptedException");
687     afe.initCause(ie);
688     throw afe;
689     }
690     }
691    
692     /**
693 jsr166 1.88 * Spin-waits up to the specified number of milliseconds for the given
694 jsr166 1.65 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
695     */
696     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
697 jsr166 1.88 long startTime = System.nanoTime();
698 jsr166 1.65 for (;;) {
699     Thread.State s = thread.getState();
700     if (s == Thread.State.BLOCKED ||
701     s == Thread.State.WAITING ||
702 jsr166 1.67 s == Thread.State.TIMED_WAITING)
703 jsr166 1.65 return;
704 jsr166 1.67 else if (s == Thread.State.TERMINATED)
705     fail("Unexpected thread termination");
706 jsr166 1.88 else if (millisElapsedSince(startTime) > timeoutMillis) {
707 jsr166 1.67 threadAssertTrue(thread.isAlive());
708     return;
709     }
710 jsr166 1.65 Thread.yield();
711     }
712     }
713    
714     /**
715 jsr166 1.75 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
716     * state: BLOCKED, WAITING, or TIMED_WAITING.
717     */
718     void waitForThreadToEnterWaitState(Thread thread) {
719     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
720     }
721    
722     /**
723 jsr166 1.66 * Returns the number of milliseconds since time given by
724     * startNanoTime, which must have been previously returned from a
725     * call to {@link System.nanoTime()}.
726     */
727     long millisElapsedSince(long startNanoTime) {
728     return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
729     }
730 jsr166 1.68
731 jsr166 1.66 /**
732 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
733 jsr166 1.38 */
734     Thread newStartedThread(Runnable runnable) {
735     Thread t = new Thread(runnable);
736 jsr166 1.58 t.setDaemon(true);
737 jsr166 1.38 t.start();
738     return t;
739     }
740 dl 1.1
741 jsr166 1.59 /**
742     * Waits for the specified time (in milliseconds) for the thread
743     * to terminate (using {@link Thread#join(long)}), else interrupts
744     * the thread (in the hope that it may terminate later) and fails.
745     */
746     void awaitTermination(Thread t, long timeoutMillis) {
747     try {
748     t.join(timeoutMillis);
749     } catch (InterruptedException ie) {
750     threadUnexpectedException(ie);
751     } finally {
752 jsr166 1.83 if (t.getState() != Thread.State.TERMINATED) {
753 jsr166 1.59 t.interrupt();
754     fail("Test timed out");
755     }
756     }
757     }
758    
759 jsr166 1.75 /**
760     * Waits for LONG_DELAY_MS milliseconds for the thread to
761     * terminate (using {@link Thread#join(long)}), else interrupts
762     * the thread (in the hope that it may terminate later) and fails.
763     */
764     void awaitTermination(Thread t) {
765     awaitTermination(t, LONG_DELAY_MS);
766     }
767    
768 dl 1.1 // Some convenient Runnable classes
769    
770 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
771     protected abstract void realRun() throws Throwable;
772 jsr166 1.35
773     public final void run() {
774     try {
775     realRun();
776     } catch (Throwable t) {
777     threadUnexpectedException(t);
778     }
779     }
780     }
781    
782 jsr166 1.45 public abstract class RunnableShouldThrow implements Runnable {
783     protected abstract void realRun() throws Throwable;
784 jsr166 1.40
785     final Class<?> exceptionClass;
786    
787     <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
788     this.exceptionClass = exceptionClass;
789     }
790    
791     public final void run() {
792     try {
793     realRun();
794     threadShouldThrow(exceptionClass.getSimpleName());
795     } catch (Throwable t) {
796     if (! exceptionClass.isInstance(t))
797     threadUnexpectedException(t);
798     }
799     }
800     }
801    
802 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
803     protected abstract void realRun() throws Throwable;
804 jsr166 1.40
805     final Class<?> exceptionClass;
806    
807     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
808     this.exceptionClass = exceptionClass;
809     }
810    
811     public final void run() {
812     try {
813     realRun();
814     threadShouldThrow(exceptionClass.getSimpleName());
815     } catch (Throwable t) {
816     if (! exceptionClass.isInstance(t))
817     threadUnexpectedException(t);
818     }
819     }
820     }
821    
822 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
823     protected abstract void realRun() throws Throwable;
824 jsr166 1.35
825     public final void run() {
826     try {
827     realRun();
828 jsr166 1.40 threadShouldThrow("InterruptedException");
829 jsr166 1.35 } catch (InterruptedException success) {
830 jsr166 1.81 threadAssertFalse(Thread.interrupted());
831 jsr166 1.35 } catch (Throwable t) {
832     threadUnexpectedException(t);
833     }
834     }
835     }
836    
837 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
838     protected abstract T realCall() throws Throwable;
839 jsr166 1.35
840     public final T call() {
841     try {
842     return realCall();
843     } catch (Throwable t) {
844     threadUnexpectedException(t);
845 jsr166 1.53 return null;
846 jsr166 1.35 }
847 jsr166 1.40 }
848     }
849    
850 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
851     implements Callable<T> {
852 jsr166 1.45 protected abstract T realCall() throws Throwable;
853 jsr166 1.40
854     public final T call() {
855     try {
856     T result = realCall();
857     threadShouldThrow("InterruptedException");
858     return result;
859     } catch (InterruptedException success) {
860 jsr166 1.81 threadAssertFalse(Thread.interrupted());
861 jsr166 1.40 } catch (Throwable t) {
862     threadUnexpectedException(t);
863     }
864     return null;
865 jsr166 1.35 }
866     }
867    
868 jsr166 1.45 public static class NoOpRunnable implements Runnable {
869 dl 1.1 public void run() {}
870     }
871    
872 jsr166 1.45 public static class NoOpCallable implements Callable {
873 dl 1.1 public Object call() { return Boolean.TRUE; }
874 dl 1.10 }
875    
876 jsr166 1.45 public static final String TEST_STRING = "a test string";
877 dl 1.10
878 jsr166 1.45 public static class StringTask implements Callable<String> {
879 dl 1.10 public String call() { return TEST_STRING; }
880     }
881    
882 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
883     return new CheckedCallable<String>() {
884 jsr166 1.64 protected String realCall() {
885 jsr166 1.48 try {
886     latch.await();
887     } catch (InterruptedException quittingTime) {}
888     return TEST_STRING;
889     }};
890     }
891    
892 jsr166 1.73 public Runnable awaiter(final CountDownLatch latch) {
893     return new CheckedRunnable() {
894     public void realRun() throws InterruptedException {
895 jsr166 1.79 await(latch);
896 jsr166 1.73 }};
897     }
898    
899 jsr166 1.79 public void await(CountDownLatch latch) {
900     try {
901     assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
902     } catch (Throwable t) {
903     threadUnexpectedException(t);
904     }
905     }
906    
907 jsr166 1.89 public void await(Semaphore semaphore) {
908     try {
909     assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
910     } catch (Throwable t) {
911     threadUnexpectedException(t);
912     }
913     }
914    
915 jsr166 1.81 // /**
916     // * Spin-waits up to LONG_DELAY_MS until flag becomes true.
917     // */
918     // public void await(AtomicBoolean flag) {
919     // await(flag, LONG_DELAY_MS);
920     // }
921    
922     // /**
923     // * Spin-waits up to the specified timeout until flag becomes true.
924     // */
925     // public void await(AtomicBoolean flag, long timeoutMillis) {
926     // long startTime = System.nanoTime();
927     // while (!flag.get()) {
928     // if (millisElapsedSince(startTime) > timeoutMillis)
929     // throw new AssertionFailedError("timed out");
930     // Thread.yield();
931     // }
932     // }
933    
934 jsr166 1.45 public static class NPETask implements Callable<String> {
935 dl 1.10 public String call() { throw new NullPointerException(); }
936     }
937    
938 jsr166 1.45 public static class CallableOne implements Callable<Integer> {
939 dl 1.10 public Integer call() { return one; }
940 dl 1.1 }
941    
942 jsr166 1.45 public class ShortRunnable extends CheckedRunnable {
943     protected void realRun() throws Throwable {
944 dl 1.76 delay(SHORT_DELAY_MS);
945 dl 1.1 }
946     }
947    
948 jsr166 1.45 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
949     protected void realRun() throws InterruptedException {
950 dl 1.76 delay(SHORT_DELAY_MS);
951 dl 1.1 }
952     }
953    
954 jsr166 1.45 public class SmallRunnable extends CheckedRunnable {
955     protected void realRun() throws Throwable {
956 dl 1.76 delay(SMALL_DELAY_MS);
957 dl 1.1 }
958     }
959    
960 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
961     protected void realRun() {
962 dl 1.6 try {
963 dl 1.76 delay(SMALL_DELAY_MS);
964 jsr166 1.44 } catch (InterruptedException ok) {}
965 dl 1.6 }
966     }
967    
968 jsr166 1.45 public class SmallCallable extends CheckedCallable {
969     protected Object realCall() throws InterruptedException {
970 dl 1.76 delay(SMALL_DELAY_MS);
971 dl 1.1 return Boolean.TRUE;
972     }
973     }
974    
975 jsr166 1.45 public class MediumRunnable extends CheckedRunnable {
976     protected void realRun() throws Throwable {
977 dl 1.76 delay(MEDIUM_DELAY_MS);
978 dl 1.1 }
979     }
980    
981 jsr166 1.45 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
982     protected void realRun() throws InterruptedException {
983 dl 1.76 delay(MEDIUM_DELAY_MS);
984 dl 1.1 }
985     }
986    
987 jsr166 1.63 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
988     return new CheckedRunnable() {
989     protected void realRun() {
990     try {
991 dl 1.76 delay(timeoutMillis);
992 jsr166 1.63 } catch (InterruptedException ok) {}
993     }};
994     }
995    
996 jsr166 1.45 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
997     protected void realRun() {
998 dl 1.1 try {
999 dl 1.76 delay(MEDIUM_DELAY_MS);
1000 jsr166 1.44 } catch (InterruptedException ok) {}
1001 dl 1.1 }
1002     }
1003 dl 1.5
1004 jsr166 1.45 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1005     protected void realRun() {
1006 dl 1.12 try {
1007 dl 1.76 delay(LONG_DELAY_MS);
1008 jsr166 1.44 } catch (InterruptedException ok) {}
1009 dl 1.12 }
1010     }
1011    
1012 dl 1.5 /**
1013     * For use as ThreadFactory in constructors
1014     */
1015 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
1016 jsr166 1.33 public Thread newThread(Runnable r) {
1017 dl 1.5 return new Thread(r);
1018 jsr166 1.27 }
1019 dl 1.5 }
1020    
1021 jsr166 1.61 public interface TrackedRunnable extends Runnable {
1022     boolean isDone();
1023     }
1024    
1025     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1026     return new TrackedRunnable() {
1027     private volatile boolean done = false;
1028     public boolean isDone() { return done; }
1029     public void run() {
1030     try {
1031 dl 1.76 delay(timeoutMillis);
1032 jsr166 1.61 done = true;
1033     } catch (InterruptedException ok) {}
1034     }
1035     };
1036     }
1037    
1038 jsr166 1.45 public static class TrackedShortRunnable implements Runnable {
1039     public volatile boolean done = false;
1040 dl 1.5 public void run() {
1041     try {
1042 dl 1.76 delay(SHORT_DELAY_MS);
1043 jsr166 1.61 done = true;
1044     } catch (InterruptedException ok) {}
1045     }
1046     }
1047    
1048     public static class TrackedSmallRunnable implements Runnable {
1049     public volatile boolean done = false;
1050     public void run() {
1051     try {
1052 dl 1.76 delay(SMALL_DELAY_MS);
1053 dl 1.5 done = true;
1054 jsr166 1.44 } catch (InterruptedException ok) {}
1055 dl 1.6 }
1056     }
1057    
1058 jsr166 1.45 public static class TrackedMediumRunnable implements Runnable {
1059     public volatile boolean done = false;
1060 dl 1.6 public void run() {
1061     try {
1062 dl 1.76 delay(MEDIUM_DELAY_MS);
1063 dl 1.6 done = true;
1064 jsr166 1.44 } catch (InterruptedException ok) {}
1065 dl 1.6 }
1066     }
1067    
1068 jsr166 1.45 public static class TrackedLongRunnable implements Runnable {
1069     public volatile boolean done = false;
1070 dl 1.6 public void run() {
1071     try {
1072 dl 1.76 delay(LONG_DELAY_MS);
1073 dl 1.6 done = true;
1074 jsr166 1.44 } catch (InterruptedException ok) {}
1075 dl 1.6 }
1076     }
1077    
1078 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
1079     public volatile boolean done = false;
1080 dl 1.6 public void run() {
1081     done = true;
1082 dl 1.5 }
1083     }
1084    
1085 jsr166 1.45 public static class TrackedCallable implements Callable {
1086     public volatile boolean done = false;
1087 dl 1.5 public Object call() {
1088     try {
1089 dl 1.76 delay(SMALL_DELAY_MS);
1090 dl 1.5 done = true;
1091 jsr166 1.44 } catch (InterruptedException ok) {}
1092 dl 1.5 return Boolean.TRUE;
1093     }
1094     }
1095 dl 1.14
1096 jsr166 1.53 /**
1097     * Analog of CheckedRunnable for RecursiveAction
1098     */
1099     public abstract class CheckedRecursiveAction extends RecursiveAction {
1100     protected abstract void realCompute() throws Throwable;
1101    
1102     public final void compute() {
1103     try {
1104     realCompute();
1105     } catch (Throwable t) {
1106     threadUnexpectedException(t);
1107     }
1108     }
1109     }
1110    
1111     /**
1112     * Analog of CheckedCallable for RecursiveTask
1113     */
1114     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1115     protected abstract T realCompute() throws Throwable;
1116    
1117     public final T compute() {
1118     try {
1119     return realCompute();
1120     } catch (Throwable t) {
1121     threadUnexpectedException(t);
1122     return null;
1123     }
1124     }
1125     }
1126 dl 1.5
1127     /**
1128     * For use as RejectedExecutionHandler in constructors
1129     */
1130 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
1131 jsr166 1.35 public void rejectedExecution(Runnable r,
1132     ThreadPoolExecutor executor) {}
1133 dl 1.5 }
1134 jsr166 1.27
1135 jsr166 1.60 /**
1136 jsr166 1.86 * A CyclicBarrier that uses timed await and fails with
1137     * AssertionFailedErrors instead of throwing checked exceptions.
1138 jsr166 1.60 */
1139     public class CheckedBarrier extends CyclicBarrier {
1140     public CheckedBarrier(int parties) { super(parties); }
1141    
1142     public int await() {
1143     try {
1144 jsr166 1.86 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1145     } catch (TimeoutException e) {
1146     throw new AssertionFailedError("timed out");
1147 jsr166 1.60 } catch (Exception e) {
1148     AssertionFailedError afe =
1149     new AssertionFailedError("Unexpected exception: " + e);
1150     afe.initCause(e);
1151     throw afe;
1152     }
1153     }
1154     }
1155    
1156 jsr166 1.81 void checkEmpty(BlockingQueue q) {
1157 jsr166 1.72 try {
1158     assertTrue(q.isEmpty());
1159     assertEquals(0, q.size());
1160     assertNull(q.peek());
1161     assertNull(q.poll());
1162     assertNull(q.poll(0, MILLISECONDS));
1163     assertEquals(q.toString(), "[]");
1164     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1165     assertFalse(q.iterator().hasNext());
1166     try {
1167     q.element();
1168     shouldThrow();
1169     } catch (NoSuchElementException success) {}
1170     try {
1171     q.iterator().next();
1172     shouldThrow();
1173     } catch (NoSuchElementException success) {}
1174     try {
1175     q.remove();
1176     shouldThrow();
1177     } catch (NoSuchElementException success) {}
1178     } catch (InterruptedException ie) {
1179     threadUnexpectedException(ie);
1180     }
1181     }
1182    
1183 jsr166 1.79 @SuppressWarnings("unchecked")
1184 jsr166 1.81 <T> T serialClone(T o) {
1185 jsr166 1.79 try {
1186     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1187     ObjectOutputStream oos = new ObjectOutputStream(bos);
1188     oos.writeObject(o);
1189     oos.flush();
1190     oos.close();
1191 jsr166 1.87 ObjectInputStream ois = new ObjectInputStream
1192     (new ByteArrayInputStream(bos.toByteArray()));
1193     T clone = (T) ois.readObject();
1194     assertSame(o.getClass(), clone.getClass());
1195     return clone;
1196 jsr166 1.79 } catch (Throwable t) {
1197     threadUnexpectedException(t);
1198     return null;
1199     }
1200     }
1201 dl 1.1 }