ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.238
Committed: Mon Dec 11 00:27:08 2017 UTC (6 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.237: +5 -12 lines
Log Message:
simplify atLeastJava9, atLeastJava10

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