ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.117
Committed: Mon Jun 9 18:17:37 2014 UTC (9 years, 10 months ago) by jsr166
Branch: MAIN
Changes since 1.116: +1 -1 lines
Log Message:
millisElapsedSince should be static

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