ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.239
Committed: Tue Jan 23 20:44:11 2018 UTC (6 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.238: +51 -69 lines
Log Message:
migrate from AssertionFailedError to AssertionError

File Contents

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