ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.145
Committed: Fri Sep 25 05:41:29 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.144: +8 -7 lines
Log Message:
optimize runTestProfiled

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