ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.84
Committed: Sat May 28 22:19:27 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.83: +1 -1 lines
Log Message:
new Date().getTime() ==> System.currentTimeMillis()

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