ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.213
Committed: Fri Dec 9 06:58:57 2016 UTC (7 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.212: +11 -4 lines
Log Message:
run conformance mode tests with stricter @modules

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